Memoization in JavaScript: Optimizing Functions for LeetCode Solutions ✅

· 1 phút để đọc· Phan Thành Công
Thumbnail

Explanation

Memoization is particularly useful for functions with expensive or repetitive computations, such as those involved in dynamic programming. The key idea is to cache the results of function calls and return the cached result when the same inputs occur again.

JavaScript Implementation

Here’s how you can implement a memoized function in JavaScript:

/**
 * Memoizes a given function.
 * @param {Function} fn - The function to memoize.
 * @returns {Function} - The memoized function.
 */
function memoize(fn) {
    const cache = new Map();
    return function(...args) {
        const key = JSON.stringify(args);
        if (cache.has(key)) {
            return cache.get(key);
        }

        const result = fn(...args);
        cache.set(key, result);
        return result;
    };
}

Usage Example

Consider a function to compute the nth Fibonacci number, which can benefit significantly from memoization:

const fib = memoize(function(n) {
    if (n <= 1) return n;
    return fib(n - 1) + fib(n - 2);
});

console.log(fib(50)); // Output: 12586269025 & calculate
console.log(fib(50)); // Output: 12586269025 & I return data cached

Explanation of the Code

1. Memoize Function:

• The memoize function takes another function fn as input.

• It creates a cache (using a Map) to store the results of previous function calls.

2. Inner Function:

• The returned function converts its arguments into a JSON string (key).

• If the cache already has the key, it returns the cached result.

• Otherwise, it calls the original function fn, stores the result in the cache, and then returns the result.

Benefits

• Performance: Reduces the time complexity of expensive recursive functions by avoiding redundant calculations.

• Efficiency: Especially useful in problems involving dynamic programming, where overlapping subproblems exist.

Phan Thành Công

Phan Thành Công

Lập trình viên đam mê và sáng tạo, cùng với vai trò là YouTuber, Blogger, và TikToker.


Copyright © 2024 AnhDangCode. All rights reserved.
Phan Thành Công· Github
youtubeyoutubeyoutube