I was given this question by a prospective client to solve and I wasn't able to on time, only the makeSFns function can be altered and as I was altering to give specific square values to match the square function (based on position in arr) I kept getting the error of funcs[i] is not a function which is weird because the square function its being compared to is returning a number, how does something that's expecting a function match a number?
//Task: fix makeSFns function to show correct answer
var arr = [ Math.random(), Math.random(), Math.random(), Math.random() ];
var square = function (x) { return x * x; };
function makeSFns(arr, square) {
var fns = [];
for (var i = 0; i < arr.length; i++) {
fns.push(function() {
return square(arr[i]);
});
}
return fns;
}
var funcs = makeSFns(arr, square);
isEqual = true;
for (var i = 0; i < arr.length; i++) {
if (funcs[i]() !== square(arr[i])) {
isEqual = false;
console.log('wrong answer');
break;
}
}
if (isEqual) console.log('correct answer');
Some asking how I got the error, I tried finding a way to get position in arr and then returning
var position = 0; //outside the function
for (var i = 0; i < arr.length; i++) {
return square(arr[i]); //replacing the push function
position + 1;
}
funcsended up being empty, sofuncs[i]wasundefined, which is not a function.I kept getting the error... run your snippet ... no such error ... the code you posted in the question is obviously not the code that produces the error ... as an aside ...var i->let ifuncs[i] is not a function.