forked from ipld/js-ipld-garbage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
to-string.js
36 lines (34 loc) · 949 Bytes
/
to-string.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { CID } from 'multiformats/cid'
/**
* @param {any} obj
* @returns {string}
*/
export function toString (obj) {
if (CID.asCID(obj)) {
return `CID.parse('${obj.toString()}')`
}
if (obj === null) {
return 'null'
}
const typ = typeof obj
if (typ === 'string') {
return `'${JSON.stringify(obj).replace(/^"|"$/g, '').replace(/'/g, '\\\'')}'`
}
if (typ === 'number' || typ === 'boolean') {
return String(obj)
}
if (Array.isArray(obj)) {
return `[${obj.map(toString).join(',')}]`
}
if (obj instanceof Uint8Array) {
return `Uint8Array.from([${obj.join(',')}])`
}
if (typ === 'object') {
const props = Object.entries(obj).map(([key, value]) => {
return `[${toString(key)}]: ${toString(value)}`
})
return `{${props.join(',')}}`
}
throw new Error(`Invalid IPLD kind: ${Object.prototype.toString.call(obj)}`)
}
// console.log(toString(garbage(100, { weights: { list: 0 } })))