Questions
2.1 No extra variables: Our functional implementation required using an extra variable, done
, to mark whether the function had already been called. Not that it matters, but could you make do without using any extra variables? Note that we aren’t telling you not to use any variables, it’s just a matter of not adding any new ones, such as done
, and only as an exercise!
2.2 Alternating functions: In the spirit of our onceAndAfter()
function, can you write an alternator()
higher-order function that gets two functions as arguments and, on each call, alternatively calls one and another? The expected behavior should be as in the following example:
const sayA = () => console.log("A"); const sayB = () => console.log("B"); const alt = alternator(sayA, sayB); alt(); // A alt(); // B alt(); // A alt(); // B alt(); // A alt(); // B
2.3 Everything has a limit! As an extension of once()
, could you write a higher-order function, thisManyTimes(fn,n)
, that would let you call the fn()
function up to n times, but would do nothing afterward? To give an example, once(fn)
and thisManyTimes(fn,1)
would produce functions that behave the same way. Do also write tests for it.
2.4 Allow for crashing: Suppose we apply once()
to a function, and the first time that function gets called, it crashes. Here, we may want to allow a second call to the function, hoping it wouldn’t crash again. We want an onceIfSuccess()
function, that will get a function as a parameter and produce a new function that will run successfully only once, but will be allowed to fail (throwing exceptions) many times if need be. Implement onceIfSuccess()
, and don’t forget to write unit tests for it.
2.5 Say no to arrows: Implement once()
using classic functions, instead of arrow functions. This is just meant to help you explore the slightly different needed data typing syntax.