Skip to content

Instantly share code, notes, and snippets.

@wires
Last active May 20, 2016 01:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wires/a08d304692f4e8310257c69343f2ffef to your computer and use it in GitHub Desktop.
Save wires/a08d304692f4e8310257c69343f2ffef to your computer and use it in GitHub Desktop.
Lazy evaluation for synchronous JS function, 'memoization'
// 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