In this article let us create a Javascript program that will sum up all the numbers within an array that can get divided by 2. For example, in the array [1,2,3] the only number which can get divided by 2 is 2 therefore the total of the outcome is 0 + 2 + 0 = 2.
The solution to the above problem is to create an iterable class that will later return an iterator object through its [Symbol.iterator] method, the iterator object will then be used inside the for loop to repeatedly returns the iteration result object with the value property which contains a number within the array that can be divided by 2 each time the next method of the iterator object has been called. If the for loop receives the done property value as true then the loop will terminate. All other numbers within the array that cannot get divided by 2 will be set to 0.
The iterable class is as follow:-
class Twomodule { constructor(arr) { this.arr = arr; } [Symbol.iterator] () { let index = 0; let arr = this.arr; return { next() { if(index < arr.length) { if(arr[index] % 2 == 0) return {value:arr[index++]}; else { arr[index++]; return {value:0}; } } else { return {done:true}; } }, [Symbol.iterator] () { return this; } } } }
As you can see the iterable class object constructor will accept an array of numbers that will be used in the addition process later on.
The step below will create an iterator object which will get called rapidly within the for loop, to sum up, the numbers that can get divided by 2!
let sum = 0; for(let x of new Twomodule([1,2,3,4,5,7,9,2,12])) sum += x; console.log(sum) //20
As you can see the x value is actually the same as the iteration_result_object.value! There is actually another easy solution to create the same outcome but this one is just to demonstrate the use of the JavaScript iterable class.