es.array.unshift.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var toObject = require('../internals/to-object');
  4. var lengthOfArrayLike = require('../internals/length-of-array-like');
  5. var setArrayLength = require('../internals/array-set-length');
  6. var deletePropertyOrThrow = require('../internals/delete-property-or-throw');
  7. var doesNotExceedSafeInteger = require('../internals/does-not-exceed-safe-integer');
  8. // IE8-
  9. var INCORRECT_RESULT = [].unshift(0) !== 1;
  10. // V8 ~ Chrome < 71 and Safari <= 15.4, FF < 23 throws InternalError
  11. var SILENT_ON_NON_WRITABLE_LENGTH = !function () {
  12. try {
  13. // eslint-disable-next-line es/no-object-defineproperty -- safe
  14. Object.defineProperty([], 'length', { writable: false }).unshift();
  15. } catch (error) {
  16. return error instanceof TypeError;
  17. }
  18. }();
  19. // `Array.prototype.unshift` method
  20. // https://tc39.es/ecma262/#sec-array.prototype.unshift
  21. $({ target: 'Array', proto: true, arity: 1, forced: INCORRECT_RESULT || SILENT_ON_NON_WRITABLE_LENGTH }, {
  22. // eslint-disable-next-line no-unused-vars -- required for `.length`
  23. unshift: function unshift(item) {
  24. var O = toObject(this);
  25. var len = lengthOfArrayLike(O);
  26. var argCount = arguments.length;
  27. if (argCount) {
  28. doesNotExceedSafeInteger(len + argCount);
  29. var k = len;
  30. while (k--) {
  31. var to = k + argCount;
  32. if (k in O) O[to] = O[k];
  33. else deletePropertyOrThrow(O, to);
  34. }
  35. for (var j = 0; j < argCount; j++) {
  36. O[j] = arguments[j];
  37. }
  38. } return setArrayLength(O, len + argCount);
  39. }
  40. });