Last active
August 29, 2015 14:19
-
-
Save jaawerth/16381bbbd9f618174551 to your computer and use it in GitHub Desktop.
jaawerth's iterator concat (es6 generator-based)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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