CopyDataProperties.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 OwnPropertyKeys = require('../helpers/OwnPropertyKeys');
  7. var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable');
  8. var CreateDataProperty = require('./CreateDataProperty');
  9. var Get = require('./Get');
  10. var IsArray = require('./IsArray');
  11. var IsInteger = require('./IsInteger');
  12. var IsPropertyKey = require('./IsPropertyKey');
  13. var SameValue = require('./SameValue');
  14. var ToNumber = require('./ToNumber');
  15. var ToObject = require('./ToObject');
  16. var Type = require('./Type');
  17. // https://262.ecma-international.org/9.0/#sec-copydataproperties
  18. module.exports = function CopyDataProperties(target, source, excludedItems) {
  19. if (Type(target) !== 'Object') {
  20. throw new $TypeError('Assertion failed: "target" must be an Object');
  21. }
  22. if (!IsArray(excludedItems)) {
  23. throw new $TypeError('Assertion failed: "excludedItems" must be a List of Property Keys');
  24. }
  25. for (var i = 0; i < excludedItems.length; i += 1) {
  26. if (!IsPropertyKey(excludedItems[i])) {
  27. throw new $TypeError('Assertion failed: "excludedItems" must be a List of Property Keys');
  28. }
  29. }
  30. if (typeof source === 'undefined' || source === null) {
  31. return target;
  32. }
  33. var fromObj = ToObject(source);
  34. var sourceKeys = OwnPropertyKeys(fromObj);
  35. forEach(sourceKeys, function (nextKey) {
  36. var excluded = false;
  37. forEach(excludedItems, function (e) {
  38. if (SameValue(e, nextKey) === true) {
  39. excluded = true;
  40. }
  41. });
  42. var enumerable = $isEnumerable(fromObj, nextKey) || (
  43. // this is to handle string keys being non-enumerable in older engines
  44. typeof source === 'string'
  45. && nextKey >= 0
  46. && IsInteger(ToNumber(nextKey))
  47. );
  48. if (excluded === false && enumerable) {
  49. var propValue = Get(fromObj, nextKey);
  50. CreateDataProperty(target, nextKey, propValue);
  51. }
  52. });
  53. return target;
  54. };