memoize

No, that wasn't a typo. :)

memoize is a pretty cool function that relies on the fact that, for a pure function, the same inputs will always lead to the same outputs.

Here's how it works:

var add = memoize((a, b) => a + b)

//addition computed and saved
console.log(add(1, 2))

//saved result returned
console.log(add(1, 2))  

Calling this code prints out 3 and 3 just like you'd expect, but the second time add is called the computation isn't done. The cached value is returned instead.

Here are the guts of memoize:

var memoize = (f) => {  
    var cache = {}

    return function () {
        var arg_str = JSON.stringify(arguments)
        cache[arg_str] =
            cache[arg_str] || f.apply(f, arguments)
        return cache[arg_str]
    }
}

I should note that I stole this code more or less directly from Professor Frisby's Mostly Adequate Guide To Functional Programming, an online book I can't recomend highly enough.

Here's how it works: memoize returns a function that keeps the original function f and the cache cache in a closure. Any time this returned function is called, we first look to see if the stringified arguments are keys in the cache. If not, we add that key-value pair to the cach. In either case we then return the value.

Both lodash and underscore have memoize. So, if you're using one of them, you're ready to go.

A word of caution before you use this function. Just as with any any other optimization, don't memoize prematurely. :)

Looking for a software developer?