applyReviver.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. /**
  3. * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,
  4. * in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the
  5. * 2021 edition: https://tc39.es/ecma262/#sec-json.parse
  6. *
  7. * Includes extensions for handling Map and Set objects.
  8. */
  9. function applyReviver(reviver, obj, key, val) {
  10. if (val && typeof val === 'object') {
  11. if (Array.isArray(val)) {
  12. for (let i = 0, len = val.length; i < len; ++i) {
  13. const v0 = val[i];
  14. const v1 = applyReviver(reviver, val, String(i), v0);
  15. // eslint-disable-next-line @typescript-eslint/no-array-delete
  16. if (v1 === undefined)
  17. delete val[i];
  18. else if (v1 !== v0)
  19. val[i] = v1;
  20. }
  21. }
  22. else if (val instanceof Map) {
  23. for (const k of Array.from(val.keys())) {
  24. const v0 = val.get(k);
  25. const v1 = applyReviver(reviver, val, k, v0);
  26. if (v1 === undefined)
  27. val.delete(k);
  28. else if (v1 !== v0)
  29. val.set(k, v1);
  30. }
  31. }
  32. else if (val instanceof Set) {
  33. for (const v0 of Array.from(val)) {
  34. const v1 = applyReviver(reviver, val, v0, v0);
  35. if (v1 === undefined)
  36. val.delete(v0);
  37. else if (v1 !== v0) {
  38. val.delete(v0);
  39. val.add(v1);
  40. }
  41. }
  42. }
  43. else {
  44. for (const [k, v0] of Object.entries(val)) {
  45. const v1 = applyReviver(reviver, val, k, v0);
  46. if (v1 === undefined)
  47. delete val[k];
  48. else if (v1 !== v0)
  49. val[k] = v1;
  50. }
  51. }
  52. }
  53. return reviver.call(obj, key, val);
  54. }
  55. exports.applyReviver = applyReviver;