1

I'm creating a function saveOutput that accepts a function, and a string. saveOutput will then return a function that behaves exactly like the passed-in function, except for when the password string is passed in as an argument. When this happens, the returned function will return an object with all previously passed-in arguments as keys, and the corresponding outputs as values.

I think my code below is correct but I run into the Range Error: Maxiumum call stack size exceeded when I run my code.

   function saveOutput(inputFunc, string) {
      let obj = {};
      //inputFunc() accepts one args
      //string like a pwd
     return function inputFunc(input) {
        if (input === string) {
            return obj;
             } else {
            obj[input] = inputFunc(input);
            return inputFunc(input);
        }
      }
      //returns a fxn
      return inputFunc;
   }

    //Test cases
    const multiplyBy2 = function(num) { return num * 2; };
    const multBy2AndLog = saveOutput(multiplyBy2, 'boo');
    console.log(multBy2AndLog(2)); // should log: 4
    console.log(multBy2AndLog(9)); // should log: 18
    console.log(multBy2AndLog('boo')); // should log: { 2: 4, 9: 18 }
Codestudio
  • 525
  • 3
  • 5
  • 28
  • You're shadowing the argument `inputFunc` by defining a function with the same name. Use just `return function (input) { .. }` or, if you want to give this function a name, use any other name. – Titus Jul 10 '20 at 23:52

1 Answers1

3

You're using the name inputFunc twice. The returned function is called inputFunc so it shadows the callback function passed as parameter. The returned function calls inputFunc which is itself and causes an endless recursion and eventually the "maxiumum call stack size exceeded" error is thrown.

To fix this either use a different name or make it anonymous as the name is not needed anyway, here is the working code with some improvements:

function saveOutput(inputFunc, string) {
  let obj = {};

  return function (input) {                    // make it anonymous
    if (input === string) {
      return obj;
    }
                                               // improvement 1: the else block can be omitted here
    return obj[input] = inputFunc(input);      // improvement 2: no need to call inputFunc twice, just assign and return at the same time 
  }

  // the return statement here is never reached because there is a return right before it so just remove it
}

Read more about variable shadowing here: An example of variable shadowing in javascript

Demo:

function saveOutput(inputFunc, string) {
  let obj = {};

  return function(input) {
    if (input === string) {
      return obj;
    }

    return obj[input] = inputFunc(input);
  }
}

const multiplyBy2 = function(num) {
  return num * 2;
};
const multBy2AndLog = saveOutput(multiplyBy2, 'boo');
console.log(multBy2AndLog(2));
console.log(multBy2AndLog(9));
console.log(multBy2AndLog('boo'));
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73