Hello everyone, please could someone help me in understanding higher order functions? I’m having a quite hard time solving this problem
function two(){}
function three(){}
function multiply(){}
two(multiply(three())) //=> 6
I’ve tried for a while and still I cannot figure out how I should write a function in a way that will output the above result. Please provide some explanation and, if possible, links or other material to better understand the concept of a higher order function…
This is a very weird functional procedure, but if you are sure this is what you want to solve exactly that, then let us split up what needs to be done in words:
Presumably, three() needs to return the number 3
multiply will accept one argument, and return a function which also accepts one argument, and returns the product of its argument and multiply's argument.
two should accept a function as an argument, and return the output of calling this function with an argument of 2.
I am not really sure what external resources to link. So, I suggest you look into callback functions. I would not say that this example is particularly related to higher order functions.
I have a grasp of how is possible to play with callbacks, at least of the basis.
//Example 1
function outer(x = 20) {
let example = 20
function inner() {
return example * x
} return inner()
}
outer(10) // 200
outer() // 400 (because of x's default value of 20)
//Example 2
let little = a => a + 1
let bigger = b => b * 10
let evenBigger = x => x
evenBigger(bigger(little(9))) // 100
//Example 3
function fun(x) {
let random = x * 10
function moreFun() {
return random * 10
} return moreFun()
}
fun(10) // 1000
//Example 4
function A(x) {
return function B(y) {
return function C(z) {
console.log(x + y + z);
}
;
}
}
A(1)(2)(8); // logs 6 (1 + 2 + 8) (could put whatever number I want)
I know my first example isn’t accurate to depict the concept of higher order functions, but is a challenge I’d like to resolve. It’s not that hard to chain three different functions, but having it working as in the first case seems much harder to me