Skip to content

Instantly share code, notes, and snippets.

@jbrechtel
Last active February 26, 2019 15:59
Show Gist options
  • Save jbrechtel/da05e6383ccf682f183d to your computer and use it in GitHub Desktop.
Save jbrechtel/da05e6383ccf682f183d to your computer and use it in GitHub Desktop.
generators?
function mapComp(array, fn) {
var result = [];
for(var i = 0; i < array.length; i++) {
result.push(fn(i));
}
return result;
}
function identity(i) { return i; };
function compose(composed, composees) {
if(composees.length === 0) {
return composed;
} else {
console.log(composees.length);
var fn = composees[0];
var newComposed = function(i) {
return fn(composed(i));
};
return compose(newComposed, composees.slice(1));
}
}
var items = [];
for(var i = 0; i < 500000; i++) {
items[i] = i;
}
var dbl = function(i) { return i * 2; };
var square = function(i) { return i * i; };
var minus50 = function(i) { return i - 50; };
console.time("mapComp");
mapComp(items, compose(identity, [dbl, square, minus50]));
console.timeEnd("mapComp");
function* mapGen(gen, fn) {
var item = gen.next();
while(!item.done) {
yield(fn(item.value));
item = gen.next();
}
}
function* itemsGen() {
for(var i = 0; i < 500000; i++) {
yield i;
}
}
function toArray(gen) {
var items = [];
var item = gen.next();
while(!item.done) {
items.push(item.value);
item = gen.next();
}
return items;
}
var dbl = function(i) { return i * 2; };
var square = function(i) { return i * i; };
var minus50 = function(i) { return i - 50; };
console.time("mapGen");
toArray(mapGen(mapGen(mapGen(itemsGen(), dbl), square), minus50));
console.timeEnd("mapGen");
<html>
<body>
<script type="text/javascript" src="generators.js">
</script>
<script type="text/javascript" src="composition.js">
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment