array-copy-within.js 1.0 KB

123456789101112131415161718192021222324252627282930
  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 min = Math.min;
  6. // `Array.prototype.copyWithin` method implementation
  7. // https://tc39.es/ecma262/#sec-array.prototype.copywithin
  8. // eslint-disable-next-line es-x/no-array-prototype-copywithin -- safe
  9. module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) {
  10. var O = toObject(this);
  11. var len = lengthOfArrayLike(O);
  12. var to = toAbsoluteIndex(target, len);
  13. var from = toAbsoluteIndex(start, len);
  14. var end = arguments.length > 2 ? arguments[2] : undefined;
  15. var count = min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to);
  16. var inc = 1;
  17. if (from < to && to < from + count) {
  18. inc = -1;
  19. from += count - 1;
  20. to += count - 1;
  21. }
  22. while (count-- > 0) {
  23. if (from in O) O[to] = O[from];
  24. else delete O[to];
  25. to += inc;
  26. from += inc;
  27. } return O;
  28. };