1

Objective

Write a function values(f, low, high) that yields an array of function values [f(low), f(low + 1), . . ., f(high)].

What I Tried

function values(f, low, high) {
  var result = [];

  for(var i = low; i < high; i++) {
    result.push(j = f(i));
  }

  return result;
}

const vf = (p1) => console.log(p1);

const arrayOfFuns = values(vf, 10, 16);

console.log(arrayOfFuns);
console.log(arrayOfFuns[0]());

Expected Output

10
11
12
13
14
15
[ function, function, function, function, function, function ]
10 // console.log(arrayOfFuns[0]());

Output

10
11
12
13
14
15
[ undefined, undefined, undefined, undefined, undefined, undefined ]
/home/moss/var/Modern JS for the Impatient/3.3.js:16
console.log(arrayOfFuns[0]());
                          ^

TypeError: arrayOfFuns[0] is not a function
    at Object.<anonymous> (/home/moss/var/Modern JS for the Impatient/3.3.js:16:27)
    at Module._compile (internal/modules/cjs/loader.js:1072:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
    at internal/main/run_main_module.js:17:47

Why is the arrayOfFuns array element filled with undefined? I thought it would be an array of functions. Also I expected that accessing the first element of arrayOfFuns would print 10.

2 Answers 2

3

I think you are looking for something like this.

I have created a function named nf which returns the ith value and pushed it in the array.

function values(f, low, high) {
  var result = [];

  for(let i = low; i < high; i++) {
    f(i);
    const nf = () => i;
    result.push(nf);
  }

  return result;
}

const vf = (p1) => console.log(p1);

const arrayOfFuns = values(vf, 10, 16);

console.log(arrayOfFuns);
console.log(arrayOfFuns[0]());

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

Comments

2

You can create an anonymous function each time.

function values(f, low, high) {
  var result = [];

  for(var i = low; i < high; i++) {
    result.push(()=> f(i));
  }

  return result;
}

const vf = (p1) => console.log(p1);

const arrayOfFuns = values(vf, 10, 16);

console.log(arrayOfFuns);
console.log(arrayOfFuns[0]());

Comments

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.