Last active
February 26, 2019 15:59
-
-
Save jbrechtel/da05e6383ccf682f183d to your computer and use it in GitHub Desktop.
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 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"); |
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* 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"); |
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
<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