0

I have a function 'sometimes' and want to return a function object from it.

Below is my code:

let add = (a, b) => {
    return a + b;
  };

myFunc = sometimes(add);

const outputArr = [];

    for (let i = 0; i < 3; i++) {
      outputArr.push(myFunc(2 + i, 3 + i));
    }

function sometimes (inputFunc){
  return function (a, b){
    return inputFunc()
  }
}

outputArr 

I expect my outputArr variable to equal:

[5, 7, 9]

Instead mine equals:

 [ NaN, NaN, NaN ]

What am I doing wrong?

1
  • 1
    You did not pass any arguments. Should be return inputFunc(a, b) Commented Jun 2, 2019 at 17:46

2 Answers 2

2

You are not passing the parameters to the wrapped function. The add function tries to sum two undefined values and the result is NaN (not a number).

You have to pass the parameters to the wrapped function:

 return function(a, b) {
    return inputFunc(a, b); // <<<
 }

Since sometimes is a higher order function, that needs to wrap different functions, with a changing number of parameters, it can't know the implementation of the wrapped function. To ensure that, you should use rest parameters (to collect the parameters to an array) and spread (to convert the array back to parameters) to pass the arguments to the wrapped function.

let add = (a, b) => {
  return a + b;
};

myFunc = sometimes(add);

const outputArr = [];

for (let i = 0; i < 3; i++) {
  outputArr.push(myFunc(2 + i, 3 + i));
}

function sometimes(inputFunc) {
  return function(...args) {
    return inputFunc(...args)
  }
}

console.log(outputArr);

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

1 Comment

Yeah, that's a better idea.
0

you can use your code as

    function sometimes(a,b){
    return a + b;
}

const outputArr = [];

    for (let i = 0; i < 3; i++) {
      outputArr.push(sometimes(2 + i, 3 + i));

    }
console.log(outputArr);

now the output is

[ 5, 7, 9 ]

1 Comment

I think you are missing the "higher order function" part of the question.

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.