So I wanted to replicate the 𝝨 function/operation in Javascript.
For the people not familiar with it, here is an example:
The above displayed operation would translate to Javascript code like this:
var sum = 0;
for (var n = 1; n <= 10; n++) {
sum += n ** 2;
}
Now I wanted to wrap it as a function, where the operation that each iteration should do would be passed as a function. So the example above would be passed like this:
𝝨(1, 10, n => n ** 2)
function 𝝨(start, end, func) {
var sum = 0;
for (var i = start; i <= end; i++) {
sum += func();
}
return sum;
}
However, the above example returns NaN because the variable passed doesn't use the iterator of the for-loop. Is there a way to do that?
You're not passing in the iterative value to the callback func:
for (var i = start; i <= end; i++) {
sum += func(i); // you have to pass it in so func knows how to func
}
But why do we want func()? This works fine too I guess. It outputs the same answer 385.
function 𝝨(start, end){
let sum = 0;
for (let n = start; n <= end; n++) {
sum += n ** 2;
}
return sum;
}
alert(𝝨(1, 10));