es.array.iterator.js 2.5 KB

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