InternalizeJSONProperty.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. var $TypeError = require('es-errors/type');
  3. var Call = require('./Call');
  4. var CreateDataProperty = require('./CreateDataProperty');
  5. var EnumerableOwnProperties = require('./EnumerableOwnProperties');
  6. var Get = require('./Get');
  7. var IsArray = require('./IsArray');
  8. var ToLength = require('./ToLength');
  9. var ToString = require('./ToString');
  10. var Type = require('./Type');
  11. var forEach = require('../helpers/forEach');
  12. // https://262.ecma-international.org/8.0/#sec-internalizejsonproperty
  13. // note: `reviver` was implicitly closed-over until ES2020, where it becomes a third argument
  14. module.exports = function InternalizeJSONProperty(holder, name, reviver) {
  15. if (Type(holder) !== 'Object') {
  16. throw new $TypeError('Assertion failed: `holder` is not an Object');
  17. }
  18. if (typeof name !== 'string') {
  19. throw new $TypeError('Assertion failed: `name` is not a String');
  20. }
  21. if (typeof reviver !== 'function') {
  22. throw new $TypeError('Assertion failed: `reviver` is not a Function');
  23. }
  24. var val = Get(holder, name); // step 1
  25. if (Type(val) === 'Object') { // step 2
  26. var isArray = IsArray(val); // step 2.a
  27. if (isArray) { // step 2.b
  28. var I = 0; // step 2.b.i
  29. var len = ToLength(Get(val, 'length')); // step 2.b.ii
  30. while (I < len) { // step 2.b.iii
  31. var newElement = InternalizeJSONProperty(val, ToString(I), reviver); // step 2.b.iv.1
  32. if (typeof newElement === 'undefined') { // step 2.b.iii.2
  33. delete val[ToString(I)]; // step 2.b.iii.2.a
  34. } else { // step 2.b.iii.3
  35. CreateDataProperty(val, ToString(I), newElement); // step 2.b.iii.3.a
  36. }
  37. I += 1; // step 2.b.iii.4
  38. }
  39. } else { // step 2.c
  40. var keys = EnumerableOwnProperties(val, 'key'); // step 2.c.i
  41. forEach(keys, function (P) { // step 2.c.ii
  42. // eslint-disable-next-line no-shadow
  43. var newElement = InternalizeJSONProperty(val, P, reviver); // step 2.c.ii.1
  44. if (typeof newElement === 'undefined') { // step 2.c.ii.2
  45. delete val[P]; // step 2.c.ii.2.a
  46. } else { // step 2.c.ii.3
  47. CreateDataProperty(val, P, newElement); // step 2.c.ii.3.a
  48. }
  49. });
  50. }
  51. }
  52. return Call(reviver, holder, [name, val]); // step 3
  53. };