Skip to content

Instantly share code, notes, and snippets.

@MKRhere
Last active December 12, 2018 05:40
Show Gist options
  • Save MKRhere/30acef4e7fa953bd5ebc3ca1851e3829 to your computer and use it in GitHub Desktop.
Save MKRhere/30acef4e7fa953bd5ebc3ca1851e3829 to your computer and use it in GitHub Desktop.
List comprehension in JavaScript
/* --------------vy::comp----------------- */
const comp = (f, iter, cond = () => true, count = Infinity) => {
const list = [];
for (const item of iter) {
if (cond(item)) list.push(f(item));
if (list.length === count) break;
}
return list;
};
/* --------------------------------------- */
/* ------------vy::compGen---------------- */
const compGen = (f, iter, cond = () => true) => {
return function* () {
for (const item of iter)
if (cond(item))
yield(f(item));
}();
};
/* --------------------------------------- */
function* naturalNumbers () {
let i = 1;
while(true) yield i++;
}
console.log(comp(x => x, naturalNumbers(), x => x % 2 === 0, 10));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment