applyReviver.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. // eslint-disable-next-line @typescript-eslint/no-array-delete
  15. if (v1 === undefined)
  16. delete val[i];
  17. else if (v1 !== v0)
  18. val[i] = v1;
  19. }
  20. }
  21. else if (val instanceof Map) {
  22. for (const k of Array.from(val.keys())) {
  23. const v0 = val.get(k);
  24. const v1 = applyReviver(reviver, val, k, v0);
  25. if (v1 === undefined)
  26. val.delete(k);
  27. else if (v1 !== v0)
  28. val.set(k, v1);
  29. }
  30. }
  31. else if (val instanceof Set) {
  32. for (const v0 of Array.from(val)) {
  33. const v1 = applyReviver(reviver, val, v0, v0);
  34. if (v1 === undefined)
  35. val.delete(v0);
  36. else if (v1 !== v0) {
  37. val.delete(v0);
  38. val.add(v1);
  39. }
  40. }
  41. }
  42. else {
  43. for (const [k, v0] of Object.entries(val)) {
  44. const v1 = applyReviver(reviver, val, k, v0);
  45. if (v1 === undefined)
  46. delete val[k];
  47. else if (v1 !== v0)
  48. val[k] = v1;
  49. }
  50. }
  51. }
  52. return reviver.call(obj, key, val);
  53. }
  54. export { applyReviver };