Is it bad practice to define values of the memo in a recursive function?

I was following along with the dynamic programming course on YouTube (Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges - YouTube at 31:50) and I made the default memo have values of 1 and 2 so that the if statement second if would not be needed (my line 3). Is it bad practice to define values within memo in the function declaration because they could get overridden if the function was run as fib(5, {"1": 10, "2: 20})?

const fib = (n, memo = {"1": 1, "2": 1}) => {
  if(n in memo) return memo[n];
  // if (n <= 2) return 1; Not needed since memo already includes these
  memo[n] = fib(n - 1, memo) + fib(n - 2, memo);
  return memo[n];

You are leaving n<=0 un-handled, so your function will have an issue with un-friendly users.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.