InternalizeJSONProperty.js 2.1 KB

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