Skip to content

Instantly share code, notes, and snippets.

@Grohden
Last active October 6, 2021 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Grohden/927d522a0e65076f8993c28df6879742 to your computer and use it in GitHub Desktop.
Save Grohden/927d522a0e65076f8993c28df6879742 to your computer and use it in GitHub Desktop.
simple impl of shortcut fusion(also called: deflorestation, stream fusion) using javascript generators
function* map(morphism, itr) {
let value;
while(value = itr.next().value) {
yield morphism(value);
}
}
function* filter(predicate, itr) {
let value;
while(value = itr.next().value) {
if(predicate(value)) {
yield value;
}
}
}
function toItr(list){
return list[Symbol.iterator]()
}
function first(itr) {
return itr.next().value
}
function toList(itr) {
let value;
let all = []
while(value = itr.next().value) {
all.push(value);
}
return all
}
const itrList = toItr([1,2,3,4,5,6,7,8,9])
// Will not run map or filter for 4,5,6,7,8,9
// because of the consumer (first) only asks for the first
// item
first(
map(
x => {
console.log('map', x); // 3
return x + 1;
},
filter(x => {
console.log('filter', x); // 1, 2, 3
return x >= 3
}, itrList)
))) // 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment