Last active
May 20, 2016 01:01
-
-
Save wires/a08d304692f4e8310257c69343f2ffef to your computer and use it in GitHub Desktop.
Lazy evaluation for synchronous JS function, 'memoization'
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
// synchronous lazy eval | |
// ES6 | |
// function lazy (ev) { return x => this.cache = this.cache || ev(x) } | |
function Lazy(ev) { | |
return function (x) { | |
return this.cache = this.cache || ev(x) | |
}.bind(this) | |
} | |
function slow (n) { | |
var s = process.uptime() | |
while(process.uptime() < s + 2); | |
return 2*n | |
} | |
var a = new Lazy(slow) | |
// takes two seconds | |
var b = a(3) | |
console.log(b) | |
// instant, returned from cache | |
var b2 = a(3) | |
console.log(b2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment