Created
October 25, 2018 21:43
-
-
Save miladvafaeifard/8ad80b6ae2a1d26ac86a0c6dffb52595 to your computer and use it in GitHub Desktop.
lazy evaluation
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
let random = function*() { | |
while(true) { | |
console.log("make random") | |
yield Math.random(); | |
} | |
} | |
let filter = function*(items, predicate) { | |
for(let item of items){ | |
console.log("filter", item); | |
if(predicate(item)){ | |
yield item; | |
} | |
} | |
}; | |
let take = function*(items, number) { | |
let count = 0; | |
if(number < 1) return; | |
for(let item of items){ | |
console.log("take", item); | |
yield item; | |
count += 1; | |
if(count >= number) { | |
console.log('finished'); | |
return; | |
} | |
} | |
}; | |
let result = take(filter(random(), n => n < 0.5), 4); | |
// console.log(Array.from(result)); | |
//Array.from is equivalent to for of | |
for( item of result ) { | |
console.log('item: ', item); | |
} | |
for( item of result ) { | |
console.log('item: ', item); // no more vaules available | |
} | |
// console.log(Array.(result).length); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An interesting thing is that 'result' variable will be empty array after you use the variable once in loop