๐Ÿ’พmemoize(f)

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

JS โŸฉ technique โŸฉ memoize โŸฉ by decorator โŸฉ ๐Ÿ’พ memoize(f)

// โญ๏ธ 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

Was this helpful?