es.string.iterator.js 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. 'use strict';
  2. var charAt = require('../internals/string-multibyte').charAt;
  3. var toString = require('../internals/to-string');
  4. var InternalStateModule = require('../internals/internal-state');
  5. var defineIterator = require('../internals/iterator-define');
  6. var createIterResultObject = require('../internals/create-iter-result-object');
  7. var STRING_ITERATOR = 'String Iterator';
  8. var setInternalState = InternalStateModule.set;
  9. var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR);
  10. // `String.prototype[@@iterator]` method
  11. // https://tc39.es/ecma262/#sec-string.prototype-@@iterator
  12. defineIterator(String, 'String', function (iterated) {
  13. setInternalState(this, {
  14. type: STRING_ITERATOR,
  15. string: toString(iterated),
  16. index: 0
  17. });
  18. // `%StringIteratorPrototype%.next` method
  19. // https://tc39.es/ecma262/#sec-%stringiteratorprototype%.next
  20. }, function next() {
  21. var state = getInternalState(this);
  22. var string = state.string;
  23. var index = state.index;
  24. var point;
  25. if (index >= string.length) return createIterResultObject(undefined, true);
  26. point = charAt(string, index);
  27. state.index += point.length;
  28. return createIterResultObject(point, false);
  29. });