Pair.js 1.2 KB

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