CatTail
12/15/2015 - 7:06 AM

It's hard to write a common memoize function in javascript

It's hard to write a common memoize function in javascript

/**
 * NOTE:
 * 1. alter return value will affect internal cache
 * 2. `uniq` implementation may cause memory leak. try WeakMap?
 */

/**
 * @return {string} unique arguments identifier
 */
function uniq() {
}

function memoize(func, context) {
    var memoized = function() {
        var args = arguments.slice(0, -1)
        var done = arguments[arguments.length]
        var key = uniq(args)
        if (!memoized.cache[key]) {
            context = context || this
            args.push(function(err) {
                // async memoized won't cache if error happend
                if (!err) memoized.cache[key] = arguments
                done.apply(null, arguments)
            })
            func.apply(context, args)
            return
        }
        callback.apply(null, memoized.cache[key])
    }
    memoized.cache = {}
    return memoized
}

function memoizeSync(func, context) {
    var memoized = function() {
        var key = uniq(arguments)
        if (!memoized.cache[key]) {
            context = context || this
            // if func throw exception cache won't exist
            memoized.cache[key] = func.apply(context, arguments)
        }
        return memoized.cache[key]
    }
    memoized.cache = {}
    return memoized
}

module.exports = {
    memoize: memoize,
    memoizeSync: memoizeSync,
}