applyReviver.js 1.8 KB

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