Loading...
Loading...
One of the most common React performance optimizations is memoization — avoiding redundant computations by caching results. This is the core idea behind React.memo, useMemo, and useCallback. In this problem, you'll implement the underlying cache mechanism that powers these hooks.
You are given a series of function calls, each identified by a function name and a list of arguments. Your task is to simulate a memoization cache that:
Each function, when called with arguments [a, b, c, ...], returns the sum of all arguments as its computed value.
Input: A list of operations, where each operation is one of:
["call", funcName, [args]] — call the function with given arguments["invalidate", funcName] — clear cached results for funcNameOutput: A list of results for each "call" operation:
"(cached)" if the result was retrieved from cache, or "(computed)" if freshly calculated.Input:
operations = [
["call", "add", [1, 2]],
["call", "add", [1, 2]],
["call", "add", [3, 4]]
]
Output: ["3 (computed)", "3 (cached)", "7 (computed)"]
Explanation: The first call to add(1,2) computes 1+2=3. The second call hits the cache. The third call with different args computes 3+4=7.
Input:
operations = [
["call", "sum", [5, 10]],
["invalidate", "sum"],
["call", "sum", [5, 10]]
]
Output: ["15 (computed)", "15 (computed)"]
Explanation: After invalidation, the cache for sum is cleared, forcing recomputation.
Input:
operations = [
["call", "fn", []],
["call", "fn", []]
]
Output: ["0 (computed)", "0 (cached)"]
Explanation: Empty args sum to 0. Second call is cached.
1 <= operations.length <= 500 funcName consists of lowercase letters only, length 1–20 0 <= args.length <= 10 -1000 <= args[i] <= 1000 At most 100 unique function names
funcName → (argsKey → result).JSON.stringify(args))."call" operations, not "invalidate".