-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringify.js
More file actions
38 lines (37 loc) · 1.06 KB
/
stringify.js
File metadata and controls
38 lines (37 loc) · 1.06 KB
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
37
38
export const stringify = (value) => {
if (typeof value === 'boolean') return value.toString()
if (value === null) return 'null'
if (value === undefined) return 'undefined'
if (typeof value === 'number') return value.toString()
if (typeof value === 'bigint') return value.toString() + 'n'
if (typeof value === 'string') {
// if (['true', 'false', 'null', 'undefined'].includes(value)) throw Error('bad string')
return escape(value)
}
if (Array.isArray(value)) return encodeArray(value)
if (typeof value === 'object') return encodeObject(value)
// function or symbol
throw Error('bad type: ' + typeof value)
}
const encodeArray = (arr) => {
let ret = ''
for (const item of arr) {
ret += '[' + stringify(item) + ']'
}
return ret
}
const encodeObject = (obj) => {
let ret = ''
for (const [key, value] of Object.entries(obj)) {
ret += escape(key) + '[' + stringify(value) + ']'
}
return ret
}
const escape = (str) => {
let ret = ''
for (const c of str) {
if (['[', ']', '`'].includes(c)) ret += '`'
ret += c
}
return ret
}