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);

5th May 2020, 11:13 PM
Shipra Waghmare
Shipra Waghmare - avatar
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.
6th May 2020, 12:24 AM
Kevin ★
+ 1
What exactly you don't understand? Which part?
5th May 2020, 11:28 PM
Kevin ★
+ 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.
7th May 2020, 7:11 AM
Kevin ★
+ 1
Shipra Waghmare 😂 Lol. You are welcome i'm glad to help.
7th May 2020, 8:40 AM
Kevin ★
0
The whole code
5th May 2020, 11:37 PM
Shipra Waghmare
Shipra Waghmare - avatar
0
Thank you so much KevinđŸ€©đŸ€© you could be a programming tutor.
7th May 2020, 8:25 AM
Shipra Waghmare
Shipra Waghmare - avatar