t0n 0.1.17 → 0.1.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/index.ts +1 -0
- package/src/json.ts +25 -0
package/package.json
CHANGED
package/src/index.ts
CHANGED
package/src/json.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
const IDENTIFIER_RE = /^[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}]*$/u
|
|
2
|
+
|
|
3
|
+
export function JSJSON(value: unknown): string {
|
|
4
|
+
if (value === null) return 'null'
|
|
5
|
+
if (value === undefined) return 'undefined'
|
|
6
|
+
|
|
7
|
+
const type = typeof value
|
|
8
|
+
|
|
9
|
+
if (type === 'string') return JSON.stringify(value)
|
|
10
|
+
if (type === 'number' || type === 'boolean') return String(value)
|
|
11
|
+
if (type === 'bigint') return `${value}n`
|
|
12
|
+
if (type === 'function') return value.toString()
|
|
13
|
+
|
|
14
|
+
if (Array.isArray(value))
|
|
15
|
+
return `[${value.map(JSJSON).join(',')}]`
|
|
16
|
+
|
|
17
|
+
if (type === 'object') {
|
|
18
|
+
const entries = Object.entries(value as Record<string, unknown>)
|
|
19
|
+
.map(([key, val]) => `${IDENTIFIER_RE.test(key) ? key : JSON.stringify(key)}:${JSJSON(val)}`)
|
|
20
|
+
|
|
21
|
+
return `{${entries.join(',')}}`
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return 'undefined'
|
|
25
|
+
}
|