0
function calc(n,func){
    let foo = [];

    for (let i = 1; i <=n; i++) {
        foo.push(i);
}
foo=foo.map(func)
return foo
}


function helloworld(x){
    let ans=calc(5,calcmystery)
    return ans

}


calcmystery=(n,x)=>(n+x*n)/(2)



I have three functions here, first is calc function, helloworld, calcmystery.

My calcmystery takes in two arguments and return a value based on the mathematical operation above.

My calc function takes in two arguments, the n parameter is to create an array of values 1-N and the func parameter to map and transform the values in each array according to the function passed into.

My helloworld function takes in one argument x, calls the calc function and return it.

My problem here is, since I only have one argument x, when i call calc inside the helloworld function, the, and when the calcmystery function inside the calc function is called, the x parameter passed into calcmystery is not the x value I passed into the hello world function. How do I fix this code, so the x value passed into is the same and always the same value passed into the helloworld function?

console.log(helloworld(2))

It should output

[1.5,3,4.5,6,7.5]

But the output is

[0.5,2,4.5,8,12.5]
  • 2
    Are you sure the expected output is `[1.5, 2, 4.5, 6, 7.5]`, and not `[1.5, 3, 4.5, 6, 7.5]`? – codemax Aug 12 '20 at 03:42
  • If you want the `x` that is passed in to `helloworld()` to be passed along to `calc()` as the first argument, change `let ans=calc(5,calcmystery)` to `let ans=calc(x,calcmystery)`. – kmoser Aug 12 '20 at 03:44

3 Answers3

2

To refer to the x passed to helloworld, the code referring to it needs to be inside the helloworld function. To accomplish that, you can create a new anonymous function inside of helloworld that uses x to call calcmystery, like the following code does:

function helloworld(x) {
  return calc(5, (n) => calcmystery(n, x));
}
1

calcmystery needs to be curried:

calcmystery= x => n => (n+x*n)/(2)

Then you call it like this:

function helloworld(x){
    let ans=calc(5, calcmystery(x)) // pass in x here
    return ans
}
hackape
  • 18,643
  • 2
  • 29
  • 57
1

Make use of closures to close over the variable x passed into the function.

How do JavaScript closures work?

In your example, you did not pass in the x variable into the calcmystery. Therefore, how will the function know what x is?

Create a closure in calcmystery to accept x.

const calcmystery = x => n => (n + x * n) / (2);

And update helloworld to this make sure of the new closure function.

function helloworld(x){
  const ans = calc(5,calcmystery(x))
  return ans;
}
codemax
  • 1,322
  • 10
  • 19