Skip to content

Instantly share code, notes, and snippets.

@suspectpart
Created February 6, 2019 14:21
Show Gist options
  • Save suspectpart/39d9d0e1d18aaca310796059791bed76 to your computer and use it in GitHub Desktop.
Save suspectpart/39d9d0e1d18aaca310796059791bed76 to your computer and use it in GitHub Desktop.
python-like generators in javascript
function* imap(iterable, func) {
for (item of iterable) {
yield func(item);
}
}
function* ifilter(iterable, predicate) {
for (item of iterable) {
if(predicate(item)) {
yield item;
}
}
}
function isome(iterable, predicate) { // [n] => boolean
for (let item of iterable) {
if (predicate(item)) {
return true;
}
}
return false;
}
const nums = range(100);
let f1 = 0;
let f2 = 0;
let f3 = 0;
let f4 = 0;
const something = nums.filter(n => {
f1++;
return n > 10;
}).filter(n => {
f2++;
return n < 90;
}).some(n => n === 11);
console.log(f1);
console.log(f2);
console.log(something);
const projection = isome(ifilter(ifilter(nums, n => {
f3++;
return n > 10;
}), n => {
f4++;
return n < 90;
}), n => n === 11);
console.log(f3);
console.log(f4);
console.log(projection);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment