es.array.iterator.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. var toIndexedObject = require('../internals/to-indexed-object');
  3. var addToUnscopables = require('../internals/add-to-unscopables');
  4. var Iterators = require('../internals/iterators');
  5. var InternalStateModule = require('../internals/internal-state');
  6. var defineProperty = require('../internals/object-define-property').f;
  7. var defineIterator = require('../internals/iterator-define');
  8. var createIterResultObject = require('../internals/create-iter-result-object');
  9. var IS_PURE = require('../internals/is-pure');
  10. var DESCRIPTORS = require('../internals/descriptors');
  11. var ARRAY_ITERATOR = 'Array Iterator';
  12. var setInternalState = InternalStateModule.set;
  13. var getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR);
  14. // `Array.prototype.entries` method
  15. // https://tc39.es/ecma262/#sec-array.prototype.entries
  16. // `Array.prototype.keys` method
  17. // https://tc39.es/ecma262/#sec-array.prototype.keys
  18. // `Array.prototype.values` method
  19. // https://tc39.es/ecma262/#sec-array.prototype.values
  20. // `Array.prototype[@@iterator]` method
  21. // https://tc39.es/ecma262/#sec-array.prototype-@@iterator
  22. // `CreateArrayIterator` internal method
  23. // https://tc39.es/ecma262/#sec-createarrayiterator
  24. module.exports = defineIterator(Array, 'Array', function (iterated, kind) {
  25. setInternalState(this, {
  26. type: ARRAY_ITERATOR,
  27. target: toIndexedObject(iterated), // target
  28. index: 0, // next index
  29. kind: kind // kind
  30. });
  31. // `%ArrayIteratorPrototype%.next` method
  32. // https://tc39.es/ecma262/#sec-%arrayiteratorprototype%.next
  33. }, function () {
  34. var state = getInternalState(this);
  35. var target = state.target;
  36. var kind = state.kind;
  37. var index = state.index++;
  38. if (!target || index >= target.length) {
  39. state.target = undefined;
  40. return createIterResultObject(undefined, true);
  41. }
  42. if (kind == 'keys') return createIterResultObject(index, false);
  43. if (kind == 'values') return createIterResultObject(target[index], false);
  44. return createIterResultObject([index, target[index]], false);
  45. }, 'values');
  46. // argumentsList[@@iterator] is %ArrayProto_values%
  47. // https://tc39.es/ecma262/#sec-createunmappedargumentsobject
  48. // https://tc39.es/ecma262/#sec-createmappedargumentsobject
  49. var values = Iterators.Arguments = Iterators.Array;
  50. // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
  51. addToUnscopables('keys');
  52. addToUnscopables('values');
  53. addToUnscopables('entries');
  54. // V8 ~ Chrome 45- bug
  55. if (!IS_PURE && DESCRIPTORS && values.name !== 'values') try {
  56. defineProperty(values, 'name', { value: 'values' });
  57. } catch (error) { /* empty */ }