Нет описания

map.js 1.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { isMap } from '../../nodes/Node.js';
  2. import { createPair } from '../../nodes/Pair.js';
  3. import { YAMLMap } from '../../nodes/YAMLMap.js';
  4. function createMap(schema, obj, ctx) {
  5. const { keepUndefined, replacer } = ctx;
  6. const map = new YAMLMap(schema);
  7. const add = (key, value) => {
  8. if (typeof replacer === 'function')
  9. value = replacer.call(obj, key, value);
  10. else if (Array.isArray(replacer) && !replacer.includes(key))
  11. return;
  12. if (value !== undefined || keepUndefined)
  13. map.items.push(createPair(key, value, ctx));
  14. };
  15. if (obj instanceof Map) {
  16. for (const [key, value] of obj)
  17. add(key, value);
  18. }
  19. else if (obj && typeof obj === 'object') {
  20. for (const key of Object.keys(obj))
  21. add(key, obj[key]);
  22. }
  23. if (typeof schema.sortMapEntries === 'function') {
  24. map.items.sort(schema.sortMapEntries);
  25. }
  26. return map;
  27. }
  28. const map = {
  29. collection: 'map',
  30. createNode: createMap,
  31. default: true,
  32. nodeClass: YAMLMap,
  33. tag: 'tag:yaml.org,2002:map',
  34. resolve(map, onError) {
  35. if (!isMap(map))
  36. onError('Expected a mapping for this tag');
  37. return map;
  38. }
  39. };
  40. export { map };