Pair.js 1.1 KB

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