UNPKG

1.23 kBJavaScriptView Raw
1'use strict';
2
3var createNode = require('../doc/createNode.js');
4var stringifyPair = require('../stringify/stringifyPair.js');
5var addPairToJSMap = require('./addPairToJSMap.js');
6var identity = require('./identity.js');
7
8function createPair(key, value, ctx) {
9 const k = createNode.createNode(key, undefined, ctx);
10 const v = createNode.createNode(value, undefined, ctx);
11 return new Pair(k, v);
12}
13class Pair {
14 constructor(key, value = null) {
15 Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR });
16 this.key = key;
17 this.value = value;
18 }
19 clone(schema) {
20 let { key, value } = this;
21 if (identity.isNode(key))
22 key = key.clone(schema);
23 if (identity.isNode(value))
24 value = value.clone(schema);
25 return new Pair(key, value);
26 }
27 toJSON(_, ctx) {
28 const pair = ctx?.mapAsMap ? new Map() : {};
29 return addPairToJSMap.addPairToJSMap(ctx, pair, this);
30 }
31 toString(ctx, onComment, onChompKeep) {
32 return ctx?.doc
33 ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep)
34 : JSON.stringify(this);
35 }
36}
37
38exports.Pair = Pair;
39exports.createPair = createPair;