Assignment: infinite Iteration
Given an infinite Iterator over all positive odd numbers named oddNumbers provide a function collect like
const collect = n => oddNumbers => ____;that returns the sum of the first n odd numbers.
Solution
const collect = n => oddNumbers => {
let sum = 0;
let count = 0;
for (const num of oddNumbers) {
sum += num;
count++;
if (count === n) {
break;
}
}
return sum;
};Your solution will be tested against:
const Iterator = (startValue, whileFn, incrementFn) => {
const next = () => {
const proceed = whileFn(startValue);
let value = undefined;
if (proceed) {
value = startValue;
startValue = incrementFn(startValue);
}
return {value: value, done: !proceed};
};
return {
[Symbol.iterator]: () => ({next})
};
};
const oddNumbers = () => Iterator(1, x => true, x => x + 2);
const _x = Math.floor(1 + Math.random() * 100);
collect(3)(oddNumbers()) === 9
&& collect(6)(oddNumbers()) === 36
&& collect(_x)(oddNumbers()) === _x * _x