Skip to content

Latest commit

 

History

History
85 lines (70 loc) · 1.66 KB

_2623. Memoize.md

File metadata and controls

85 lines (70 loc) · 1.66 KB

2623. Memoize

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : July 09, 2024

Last updated : July 09, 2024


Related Topics : N/A

Acceptance Rate : 62.77 %


Solutions

JavaScript

/**
 * @param {Function} fn
 * @return {Function}
 */
function memoize(fn) {
    const mapRef = {};
    return function(...args) {
        const key = JSON.stringify(args);
        if (!(key in mapRef)) {
            mapRef[key] = fn(...args);
        }
        return mapRef[key];
    }
}


/** 
 * let callCount = 0;
 * const memoizedFn = memoize(function (a, b) {
 *	 callCount += 1;
 *   return a + b;
 * })
 * memoizedFn(2, 3) // 5
 * memoizedFn(2, 3) // 5
 * console.log(callCount) // 1 
 */
/**
 * @param {Function} fn
 * @return {Function}
 */
function memoize(fn) {
    const mapRef = {};
    return function(...args) {
        const key = args.join(',');
        if (!(key in mapRef)) {
            mapRef[key] = fn(...args);
        }
        return mapRef[key];
    }
}


/** 
 * let callCount = 0;
 * const memoizedFn = memoize(function (a, b) {
 *	 callCount += 1;
 *   return a + b;
 * })
 * memoizedFn(2, 3) // 5
 * memoizedFn(2, 3) // 5
 * console.log(callCount) // 1 
 */