array-copy-within.js 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. 'use strict';
  2. var toObject = require('../internals/to-object');
  3. var toAbsoluteIndex = require('../internals/to-absolute-index');
  4. var lengthOfArrayLike = require('../internals/length-of-array-like');
  5. var deletePropertyOrThrow = require('../internals/delete-property-or-throw');
  6. var min = Math.min;
  7. // `Array.prototype.copyWithin` method implementation
  8. // https://tc39.es/ecma262/#sec-array.prototype.copywithin
  9. // eslint-disable-next-line es/no-array-prototype-copywithin -- safe
  10. module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) {
  11. var O = toObject(this);
  12. var len = lengthOfArrayLike(O);
  13. var to = toAbsoluteIndex(target, len);
  14. var from = toAbsoluteIndex(start, len);
  15. var end = arguments.length > 2 ? arguments[2] : undefined;
  16. var count = min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to);
  17. var inc = 1;
  18. if (from < to && to < from + count) {
  19. inc = -1;
  20. from += count - 1;
  21. to += count - 1;
  22. }
  23. while (count-- > 0) {
  24. if (from in O) O[to] = O[from];
  25. else deletePropertyOrThrow(O, to);
  26. to += inc;
  27. from += inc;
  28. } return O;
  29. };