Search code examples
javascriptclosuresjavascript-objects

How do I solve this with closure?


I want to use closure to keep track of all previous calculations and populate them into an object using closure and printing just the result, and if the password is hit, then it should console the output the whole object with the previous operations.

function saveOutput(func, magicWord) {
  let output = {};
  let outer = magicWord;

  function someWork(x) {
    if (x !== outer) {
      output.x = func(x);
      console.log(output[x]);
    } else {
      console.log(output);
    }
  }
}

// /*** Uncomment these to check your work! ***/
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 }


Solution

    • You are executing multBy2AndLog. For this to work, you need to return the someWork function from saveOutput.
    • If you want multBy2AndLog(2) to return a value, you need to return output[x] from someWork
    • output.x will add a property x to the output object. You need to use the bracket notation output[x] to add a key with value inside x (JavaScript property access: dot notation vs. brackets?)

    function saveOutput(func, magicWord) {
      let output = {};
      let outer = magicWord;
      
      // ↓ add return here
      return function someWork(x) {
        if (x !== outer) {
          output[x] = func(x); // not output.x
          return output[x]; // <- return the value from the function 
        } else {
          return output;
        }
      }
    }
    
    function multiplyBy2(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 }