Last active
October 6, 2021 14:40
-
-
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
This file contains 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
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