Skip to content

Instantly share code, notes, and snippets.

@jaawerth
Last active August 29, 2015 14:19
Show Gist options
  • Save jaawerth/16381bbbd9f618174551 to your computer and use it in GitHub Desktop.
Save jaawerth/16381bbbd9f618174551 to your computer and use it in GitHub Desktop.
jaawerth's iterator concat (es6 generator-based)
/* Concatenate iterators by wrapping them in a "parent" iterator.
* When it's consumed, to the outside world it will appear as a single
* iterator. Allows for easily-implemented lazy evaluation and immutable
* transformations.
*/
import toIterator from './iterator';
import { isArray, isIterable, isIterator } from '../types';
function concat(...items) {
// Flatten only a single argument
if (items.length === 1) return _concat(items[0]);
return _concat(toIterator(items));
}
// we hear you like iterators, so we made iterators for your iterators
function* _concat(iters) {
let iter = iters.next();
while ( !iter.done ) {
yield* iterate(iter.value);
iter = iters.next();
}
}
// iterate the "member" iterators
function* iterate (iter) {
var el = iter.next();
while (!el.done) {
yield el.value;
el = iter.next();
}
}
export default concat;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment