1

I am trying to create a higher order function in javascript someMathArray(x) { } that returns a function and takes another single argument. I want the function to take an original array, say [1,2,3,4] then apply another function for example, named mult2(a) { return a*2 }(however, I want this to work for any function I pass in. I don't want mult2(a) to be hard coded into the function) and then return an array containing [2,4,6,8]

1 Answer 1

1

Something like this?

function someMathArray(array) {
  return function(fun) {
    return array.map(fun);
  };
}

var fun = someMathArray([1,2,3,4,5]);
var output = fun(function(a) { return a*2; });
document.getElementById('output').innerHTML = JSON.stringify(output);
<div id="output"></div>

or

function someMathArray(array) {
  return array.map.bind(array);
}

var fun = someMathArray([1,2,3,4,5]);
var output = fun(function(a) { return a*2; });
document.getElementById('output').innerHTML = JSON.stringify(output);
<div id="output"></div>

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I was having trouble wrapping my head around how higher order functions work, but your answer helped me understand what they are really doing.
How would I handle the case that the array is empty?
@ilikecake1 [].map(function(a) { return a*2; }) will return empty array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.