Skip to content
Methods for working with iterators in ECMAScript
Branch: master
Clone or download
Latest commit dabd9cd May 24, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.gitignore update polyfill Feb 1, 2019
.travis.yml initial spec of map method Feb 1, 2019
.travis_github_deploy_key.enc set up build Feb 1, 2019
DETAILS.md clarify constraints that have come up Feb 16, 2019
README.md methods in readme are out of date Apr 27, 2019
package.json update polyfill Feb 1, 2019
polyfill.js add some, every, find May 24, 2019
spec.html add some, every, find May 24, 2019

README.md

Iterator Helpers

Proposal

A proposal for several interfaces that will help with general usage and consumption of iterators in ECMAScript. Many libraries and languages already provide these interfaces.

This proposal is at Stage 1 of The Process

See DETAILS.md for details on semantics decisions.

See this specification rendered here

Example usage

function* naturals() {
  let i = 0;
  while (true) {
    yield i;
    i += 1;
  }
}

const evens = naturals()
  .filter((n) => n % 2 === 0);

for (const even of evens) {
  console.log(even, 'is an even number');
}
const MyIteratorPrototype = {
  next() {},
  throw() {},
  return() {},

  // but we don't properly implement %IteratorPrototype%!!!
};

// Previously...
// Object.setPrototypeOf(MyIteratorPrototype,
//   Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));

Object.setPrototypeOf(MyIteratorPrototype, Iterator.syncPrototype);
class ObligatoryCryptocurrencyReference extends Component {
  componentWillMount() {
    const items = ticker() // returns async iterator
      .map((c) => createElement('h2', null, `${c.name}: ${c.price}`))
      .take(5) // only consume 5 items of a potentially infinite iterator
      .collect() // greedily transform async iterator into array
      .then((data) => this.setState({ data }));
  }

  render() {
    return createElement('div', null, this.state.data);
  }
}

Why not use Array.from + Array.prototype methods?

All of these methods (except for reduce and collect) are lazy. They will only consume the iterator when they need the next item from it. Especially for iterators that never end, this is key. Without generic support for any form of iterator, different iterators have to be handled differently.

Prior Art

Method Rust Python npm Itertools C#
all
any
chain
collect
count
cycle
enumerate
filter
filterMap
find
findMap
flatMap
flatten
forEach
last
map
max
min
nth
partition
peekable
position
product
reverse
scan
skip
skipWhile
stepBy
sum
take
takeWhile
unzip
zip
compress
permutations
repeat
slice
starmap
tee
compact
contains
range
reduce
sorted
unique
average
empty
except
intersect
prepend
append

Note: The method names are combined, such as toArray and collect.

You can’t perform that action at this time.