In general, you need to write the function func (a, gen), which takes 2 functions as input, a and gen, where gen is the generator function. func returns a new generator function that, with each call, takes the next value from gen and passes it through function a. Example:

function createCounter(start, step) { return function(){ if (start === undefined) start = 0; if(step === undefined) step = 1; start+=step; return start - step; }; } var counter = createCounter(1, 1); function pow(x) { return x * x; } var powGen = func(pow, counter); console.log(powGen()); // 1 console.log(powGen()); // 4 console.log(powGen()); // 9 console.log(powGen()); // 16 

At the same time, it is necessary to make it so that as a gen it was possible to specify a function with arguments, and when calling

 function add(a, b) { return a + b; } var powAdd = func(pow, add); console.log(powAdd(1, 4)); // 25 = (1 + 4) ^ 2 console.log(powAdd(2, 5)); // 49 = (2 + 5) ^ 2 

One solution:

 function func(a, gen) { return function() { return a(gen()); }; } var func1 = func( pow, createCounter(1, 1) ); func1(); // 1 func1(); // 4 func1(); // 9 func1(); // 16 func1(); // 25 

But this and other options do not withstand the conditions of the problem. I want to figure out how to write the func function body correctly. Link to the problem book (problem number 4): http://dkab.imtqy.com/jasmine-tests/?spec=4

  • one
    I'm confused where the generator should be and where it shouldn't be - Grundy
  • not much clearer it became. What is the pow function at the end? - Grundy
  • the most incomprehensible: how the func (square, add) call is possible ; if add - does not return the function generator ??? - Grundy

1 answer 1

In fact, the formulation of the problem is a bit incorrect.

Correct requirements can be found when checking:

  1. The fmap (mixin, fn) function should return a function
  2. The returned function must take any number of arguments and pass them to the functions fn
  3. should call the mixin function for the results of the fn function

For these items, it is quite simple to write the necessary function:

  1. function that returns a function:

     function fmap(mixin, fn){ return function(){ ... } } 
  2. There are several options for passing arguments to the inner function call from the outer

    1. using the apply method

       function (){ fn.apply(null, arguments); } 
    2. using the spread-operator and rest-parameters

       function (...args){ fn(...args); } 
  3. the variant is obvious: mixin(fn(...));

Total assembly can be as follows:

 function fmap(a, gen) { return function(...args){ return a(gen(...args)); } }