/
Pair.ts
47 lines (40 loc) · 1.32 KB
/
Pair.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
47
import { createNode, CreateNodeContext } from '../doc/createNode.js'
import { StringifyContext } from '../stringify/stringify.js'
import { stringifyPair } from '../stringify/stringifyPair.js'
import { addPairToJSMap } from './addPairToJSMap.js'
import { NODE_TYPE, PAIR } from './Node.js'
import { ToJSContext } from './toJS.js'
export function createPair(
key: unknown,
value: unknown,
ctx: CreateNodeContext
) {
const k = createNode(key, undefined, ctx)
const v = createNode(value, undefined, ctx)
return new Pair(k, v)
}
export class Pair<K = unknown, V = unknown> {
readonly [NODE_TYPE]: symbol
/** Always Node or null when parsed, but can be set to anything. */
key: K
/** Always Node or null when parsed, but can be set to anything. */
value: V | null
constructor(key: K, value: V | null = null) {
Object.defineProperty(this, NODE_TYPE, { value: PAIR })
this.key = key
this.value = value
}
toJSON(_?: unknown, ctx?: ToJSContext): ReturnType<typeof addPairToJSMap> {
const pair = ctx && ctx.mapAsMap ? new Map() : {}
return addPairToJSMap(ctx, pair, this)
}
toString(
ctx?: StringifyContext,
onComment?: () => void,
onChompKeep?: () => void
): string {
return ctx && ctx.doc
? stringifyPair(this, ctx, onComment, onChompKeep)
: JSON.stringify(this)
}
}