Callbacks and Closures
Homework:
- In
twice.js
, export a function that accepts a function as an argument, and returns a function that performs the given function twice. For example, if the function exported fromtwice.js
is nameddoTwice
, then passing the functionnum => num + 2
intodoTwice
should return a function that will return a number that is 4 larger than the given argument. - In
counter.js
, export a function that will accept a string as an argument. The function should return an object with the following contents: 1) As keys: Every string ever given to this instance of the function as an argument since the time it was exported, and 2) as values: The number of times the corresponding key has been given to the function as an argument. So invoking this function withJerry
should return{ Jerry: 1 }
. Running the same instance of the function withElaine
should return{ Jerry: 1, Elaine: 1 }
. Running the same instance of the function withJerry
again should return{ Jerry: 2, Elaine 1 }
. - In
saveHistory.js
, export a function that will accept two arguments in this order: 1) a string that will serve as a password, and 2) a function. The exported function should return a new function. When the new function is invoked with any argument other than the password, it will seemingly behave just like the function that was passed into the exported function as an argument. When the password is passed into the new function as an argument, the new function should return an array of all arguments ever passed into it, except for when the password was given. So if the exported function is saved into a variable calledmakeHistorySaver
, and then we invokemakeHistorySaver
with this line:const multByThree = makeHistorySaver('Bosko', num => num * 3);
, then the following invocations in the following order will yield these corresponding outputs: 1)multByThree(4)
will yield12
, 2) after that,multByThree(6)
will yield18
, 3) after that,multByThree('Bosko')
will yield[4, 6]
, 4) after that,multByThree(3)
will yield9
, 5) after that,multByThree('Bosko')
will yield[4, 6, 3]
.