array-copy-within.js 969 B

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