Last active
December 12, 2018 05:40
-
-
Save MKRhere/30acef4e7fa953bd5ebc3ca1851e3829 to your computer and use it in GitHub Desktop.
List comprehension in JavaScript
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
/* --------------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