js-vault icon indicating copy to clipboard operation
js-vault copied to clipboard

Array.map - why is there a element exists check?

Open bendtherules opened this issue 6 years ago • 2 comments

In array.map impl, why is there a element exists in the array check? What is that supposed to do? Its literally taking that value out of the array in the previous line and checking if that exists in that line.

From what i know, the in-built impl doesn't protect against array modification. Is it trying to do that? Atleast why not just check for undefined (say if length got modified).

I have got nothing against useless checks, but that check alone is bringing down the performance from o(n) to o(n**2).

bendtherules avatar Jun 06 '19 17:06 bendtherules

Not sure if I fully understand what is happening here. As per my understanding, it is happening because indexOf(undefined) is true when there is intentional undefined in the array and then it gives true even in those empty values.

Just dropping this for now: Alt is below

let test1 = [1, 2, undefined, 4]
undefined
test1.map(val => val*2)
Array(4) [ 2, 4, NaN, 8 ]

test1.newMap(val => val*2)
Array(4) [ 2, 4, NaN, 8 ]

test1[10] = 10
10
test1.newMap(val => val*2)
(11) […]
​
0: 2
​
1: 4
​
2: NaN
​
3: 8
​
4: NaN
​
5: NaN
​
6: NaN
​
7: NaN
​
8: NaN
​
9: NaN
​
10: 20
​
length: 11
​
<prototype>: Array []

test1.map(val => val*2)
(11) […]
​
0: 2
​
1: 4
​
2: NaN
​
3: 8
​
10: 20
​
length: 11
​
<prototype>: Array []

saurabhdaware avatar Oct 05 '20 13:10 saurabhdaware

The impl should have does this index exist check, instead of does this value exist.

Easiest way will be - Object.hasOwnProperty(this, index)

Better way will be index in this - because it also checks the prototype, which i think is what the native Implementation does.

bendtherules avatar Oct 05 '20 14:10 bendtherules