W
W
WhiteBachelor2018-11-17 20:24:24
JavaScript
WhiteBachelor, 2018-11-17 20:24:24

Two sets of parameters in one function? Or a function that returns another function? How to use it at all?

I was solving problems on codewars.com and came across the following problem:
I need to design a higher order function so that it extracts other functions from an array and executes them in a chain. Moreover, the input value is set ... as it is called something ... say, at the second level or order. That is:
chained([f1,f2,f3])(0)
Here is the original:

Your task is to write a higher order function for chaining together a list of unary functions. In other words, it should return a function that does a left fold on the given functions.
chained([a,b,c,d])(input)
Should yield the same result as
d(c(b(a(input))))

At first I fell into a complete stupor, it was not at all clear what this could mean, but then I remembered the chapter on higher-order functions in the Expressive JavaScript textbook and proceeded to implement from memory. In practice, I have not implemented such a confusing function before:
function chained(functions) {

  return function(input){
    console.log(input);
    var param = input;
    for (i = functions.length - 1; i >= 0; i--){
      let making = functions[i];
      param = making(param);
    }
  }

}

To which he received the following answer:
Expected: 4, instead got: undefined
Uh ... in the sense? It is clear that the received data type did not correspond to the required one, or the index was specified incorrectly. But why?
Previously, I did not implement functions of such a higher order. What I did was much simpler, and the most difficult thing I wrote was the Fibonacci number generator and the recursive analogues of forEach, map, and filter.
If someone is interested in the task .

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stockholm Syndrome, 2018-11-17
@WhiteBachelor

why do you start iterating from the end of the array?

function chained(functions) {
  return function(input) {
    for (let i = 0; i < functions.length; i++) {
      input = functions[i](input);
    }
    return input;    
  }
}

and you returnforgot, soundefined

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question