0
How is the answer 10?
const arr = ['0', '1', '4', 'a', '9', 'c', '16']; const my_obj = { [Symbol.iterator]: function*() { for(let index of arr) { yield `${index}`; } } }; const all = [...my_obj] /* Here you can replace the '[...my_obj]' with 'arr'. */ .map(i => parseInt(i, 10)) .map(Math.sqrt) .filter((i) => i < 5) /* try changing the value of 5 to 4 see what happens.*/ .reduce((i, d) => i + d); /* comment this line while you are changing the value of the line above */ console.log(all);
6 Answers
+ 2
Oh,ok.
Let's take the bottom part first replacing [...my_obj] with arr:
const all = arr ....
//map method takes a function argument and returns a new array containing the values of the original array using the function argument as mapper:
.map(i=>parseInt(i,10)) // i here is reffering to the "arr" values. this returns an array containing base10(second arg of parseInt) numeric representations of every arr values. Our result is [0,1,4, NaN,9,NaN,16] so far.
.map(Math.sqrt) // we map the previous result using ÂČâ. Our result is [0,1,2, NaN,3,NaN,4] now.
.filter( i=> i<5 ) //filter returns a new array containing only the values that make the argument function return true. Our result is [0,1,2,3,4] now because NaN < 5 is false.
.reduce((i,d)=> i+d) //reduce returns the result of the argument function applied from left to right.
0+1= 1, 1+2=3, 3+3 = 6, 6 + 4 = 10 and that's our final result.
All above methods are available on Arrays only.
+ 1
What exactly you don't understand? Which part?
+ 1
[Symbol.iterator] is a computed property that expects an interator(or generator) as value. The yielded values of that iterator are exhausted by "for of" loops and spread operator.
For example every array has a custom Symbol.iterator that yields the arrays values one by one:
for(let index of arr)
//Here index gets assigned to the next value of the arr iterator (starting from left to right).
If we want to use that functionality in non-array objects we need to define the iterator by our own.
Thus when we use [...my_obj] we are spreading the results of the generator until it's exhausted. That results are the yielded out by the "for of" loop or what is the same: the string(check the template literal ${} is enclosing "index") representation of the "arr" values.
+ 1
Shipra Waghmare đ Lol.
You are welcome i'm glad to help.
0
The whole code
0
Thank you so much Kevinđ€©đ€© you could be a programming tutor.