CopyDataProperties.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $TypeError = GetIntrinsic('%TypeError%');
  4. var callBound = require('call-bind/callBound');
  5. var forEach = require('../helpers/forEach');
  6. var every = require('../helpers/every');
  7. var some = require('../helpers/some');
  8. var OwnPropertyKeys = require('../helpers/OwnPropertyKeys');
  9. var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable');
  10. var CreateDataPropertyOrThrow = require('./CreateDataPropertyOrThrow');
  11. var Get = require('./Get');
  12. var IsArray = require('./IsArray');
  13. var IsIntegralNumber = require('./IsIntegralNumber');
  14. var IsPropertyKey = require('./IsPropertyKey');
  15. var SameValue = require('./SameValue');
  16. var ToNumber = require('./ToNumber');
  17. var ToObject = require('./ToObject');
  18. var Type = require('./Type');
  19. // https://www.ecma-international.org/ecma-262/12.0/#sec-copydataproperties
  20. module.exports = function CopyDataProperties(target, source, excludedItems) {
  21. if (Type(target) !== 'Object') {
  22. throw new $TypeError('Assertion failed: "target" must be an Object');
  23. }
  24. if (!IsArray(excludedItems) || !every(excludedItems, IsPropertyKey)) {
  25. throw new $TypeError('Assertion failed: "excludedItems" must be a List of Property Keys');
  26. }
  27. if (typeof source === 'undefined' || source === null) {
  28. return target;
  29. }
  30. var from = ToObject(source);
  31. var keys = OwnPropertyKeys(from);
  32. forEach(keys, function (nextKey) {
  33. var excluded = some(excludedItems, function (e) {
  34. return SameValue(e, nextKey) === true;
  35. });
  36. /*
  37. var excluded = false;
  38. forEach(excludedItems, function (e) {
  39. if (SameValue(e, nextKey) === true) {
  40. excluded = true;
  41. }
  42. });
  43. */
  44. var enumerable = $isEnumerable(from, nextKey) || (
  45. // this is to handle string keys being non-enumerable in older engines
  46. typeof source === 'string'
  47. && nextKey >= 0
  48. && IsIntegralNumber(ToNumber(nextKey))
  49. );
  50. if (excluded === false && enumerable) {
  51. var propValue = Get(from, nextKey);
  52. CreateDataPropertyOrThrow(target, nextKey, propValue);
  53. }
  54. });
  55. return target;
  56. };