💾memoize(f)

make a function/method "remember" its return values.

JStechniquememoizeby decorator💾 memoize(f)

(a decorator)

make a function/method "remember" it's return values.

// ⭐️ caching decorator for memoization
//    memoize (multi-argument) function/method
function memoize(f, {
    
    // ⭐️ default hash function: (join all arguments)
    //    ex: 1,2,3 --> '1,2,3' (string as key)
    hash = (...args) => args.join(),
    
    // ⭐️ log caching details
    log  = true,
    
}={}) {

    // ⭐️ prepare cache to store return values of f
    let cache = new Map();

    // ⭐️ decorated function
    // -------------------------------------------------
    // ⭐️ must use "function expression".
    // ❗ "arrow function" won't do for a method.
    return function(...args) {

        // ⭐️ get hashed key from arguments
        let key = hash(args);

        if (log) console.log(`${f.name}(${key})`);

        // ⭐️ if already cached, return the cached value immediately.
        if (cache.has(key)) {
            let value = cache.get(key);
            if (log) console.log(`  • cache: get f(${key}) → ${value}`);
            return value;
        }

        // ⭐️ otherwise: 1. evaluate 2. cache 3. return. 
        // ❗ must pass `this` context to `f` if `f` is method
        let value = f.call(this, ...args);        // 1. 

        cache.set(key, value);                    // 2.
        if (log) console.log(`  • cache: set f(${key}) ← ${value}`);
        
        return value;                             // 3.
    };
}

// export
module.exports = { memoize };

Last updated