Last active
May 5, 2017 09:53
-
-
Save medikoo/8d9047710ea6025b8d1ba3a8adf115f2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Lazy (=on-demand) zip() | |
for (const [i, x] of zip(naturalNumbers(), naturalNumbers())) { | |
console.log(i, x); | |
if (i >= 2) break; | |
} | |
// Output: | |
// 0 0 | |
// 1 1 | |
// 2 2 | |
try { | |
Array.from(naturalNumbers(), function (x, i) { | |
console.log(i, x); | |
if (i >= 2) throw new Error("Stop!"); | |
}); | |
} catch (e) {} | |
// Infinite loop | |
function* naturalNumbers() { | |
for (let n=0;; n++) { | |
yield n; | |
} | |
} | |
function zip(...iterables) { | |
const iterators = iterables.map(i => i[Symbol.iterator]()); | |
let done = false; | |
return { | |
[Symbol.iterator]() { | |
return this; | |
}, | |
next() { | |
if (!done) { | |
const items = iterators.map(i => i.next()); | |
done = items.some(item => item.done); | |
if (!done) { | |
return { value: items.map(i => i.value) }; | |
} | |
// Done for the first time: close all iterators | |
for (const iterator of iterators) { | |
if (typeof iterator.return === 'function') { | |
iterator.return(); | |
} | |
} | |
} | |
// We are done | |
return { done: true }; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment