javascriptadvanced10 minutes
Predict the Output of Complex Recursive Function with Memoization in JavaScript
Analyze a recursive JavaScript function that uses memoization and array transformations. Predict the output when the function is called with a specific argument.
Challenge prompt
Given the following JavaScript code which defines a recursive function that calculates a custom sequence with memoization and array transformations, predict the exact output of calling computeSequence(5). Explain your reasoning step-by-step.
Guidance
- • Carefully trace the recursive calls and the memoization cache's population.
- • Understand the use of array methods like map, reduce, and how they transform values at each recursion depth.
Hints
- • Break down the function into smaller parts: focus first on the base case, then on the recursive case.
- • Visualize or write down intermediate cache states after each call.
Starter code
function computeSequence(n, memo = {}) {
if (n <= 1) return [n];
if (memo[n]) return memo[n];
const prev = computeSequence(n - 1, memo);
const transformed = prev.map(x => x * n);
const sum = transformed.reduce((acc, val) => acc + val, 0);
memo[n] = [...prev, sum];
return memo[n];
}
console.log(computeSequence(5));Expected output
[0, 1, 3, 12, 60, 360]
Core concepts
recursionmemoizationarray transformationreduce method
Challenge a Friend
Send this duel to someone else and see if they can solve it.