/
json.ts
46 lines (40 loc) · 1.05 KB
/
json.ts
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
39
40
41
42
43
44
45
46
/* eslint-disable no-redeclare */
import stableStringify = require('fast-json-stable-stringify')
const UNDEFINED = 'undefined'
/**
* @internal
*/
export function stringify(input: unknown): string {
return input === undefined ? UNDEFINED : stableStringify(input)
}
/**
* @internal
*/
export function parse(input: string): any {
return input === UNDEFINED ? undefined : JSON.parse(input)
}
interface NormalizeOptions {
parse?: (input: string) => any
}
/**
* @internal
*/
export function normalize(input: string, { parse: parser = parse }: NormalizeOptions = {}): string {
let result: string | undefined
if (normalize.cache.has(input)) {
result = normalize.cache.get(input)
} else {
const data = parser(input)
result = stringify(data)
if (result === input) result = undefined
normalize.cache.set(input, result)
}
return result === undefined ? input : result
}
/**
* @internal
*/
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace normalize {
export const cache = new Map<string, string | undefined>()
}