mozilla / rhino

Rhino is an open-source implementation of JavaScript written entirely in Java
https://rhino.github.io
Other
4.11k stars 848 forks source link

Array.from does not follow spec to prioritize iterable over array-like #1518

Open tonygermano opened 1 month ago

tonygermano commented 1 month ago

According to the spec, if the object passed to Array.from has an iterator method with a Symbol.iterator key, then that should be used before checking for a length property to see if the object is array-like. This is true even for native arrays.

function test() {
    let counter = 0
    Array.prototype[Symbol.iterator] = function* () {
        for (let i = 0; i < this.length; i++) {counter++; yield this[i]}
    }
    Array.from(['a','b','c'])
    return counter
}

In Chrome

console.log(test())
3

Rhino

js> print(test())
0
tonygermano commented 1 month ago

In regard to #1128 , the optimization could probably still be performed for a NativeArray if we check that the value stored in the Symbol.iterator property still points to the built-in iterator method and has not been changed by the user.