0

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 }
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71

1 Answers1

0
  • 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 }
adiga
  • 34,372
  • 9
  • 61
  • 83
  • Oh I see now the error I was making, I was still comparing the magicword while I already backpacked it to the closure. Thank you for the answer – Yahya Elfaqir Sep 19 '20 at 14:41