Re: toArray() method for array-like DOM list objects

On 12/22/11 6:57 PM, Marat Tanalin | tanalin.com wrote:
> It's very questionable why someone should want to convert Array to same Array.

Because they don't want to have to worry about whether the caller passed 
in the result of some jQuery operation or some DOM nodelist.

I think you're assuming that the same person is writing the caller in 
both the caller and callee.  This is generally a bad assumption in my 
experience.

> That would be just waste of computer power and should not be allowed anyway.

Why the heck not?

> By the way, that's what is the key difference between what Array.slice() is intended for and its workaround use for arrayLike-to-Array conversion. Calling Array.slice(0) is exactly as pointless as Array.toArray() would be.

It's not pointless at all: it make a copy of the input array, that you 
can then modify as desired without messing up the object the caller sees.

>> Or this object:
>>     { length: 2, 0: "a", 1: "b" }
>
> Result of calling Array.prototype.slice.call() for this object is unlikely to be desired:
> [a,b]

Why is that unlikely to be desired?  That's exactly the Array object 
that has the same behavior when iterated from 0 to length as the 
original array.

> Direct conversion to Array is probably just inapplicable here.

Why not?

>> I doubt you're really appreciate NodeList and HTMLCollection having
>> different APIs, even if they were documented...
>
> Oh, NodeList and HTMLCollection are actually nearly identical things from web-developers point.

Precisely.  But how is [a, b] really different from { length: 2, 0: "a", 
1: "b" } from a web-developer perspective?

>> This ambiguity already exists for numbers, yes?  Why is a separate
>> argument not needed there, apart from the "it's always been that way"
>> argument.
>
> What exact ambiguity do you mean as for numbers? Could you provide an example?

Sure.  What do you think

   new Array(5)

does?  How does that compare to

   new Array("x")

?

>> It would be better for cases when you're working with arbitrary
>> arraylikes which may or may not be nodelists, for sure.
>
> Well, I see. I'm talking about DOM here, though.

But the DOM is not used in isolation.  You're talking about converting 
DOM nodelists to arrays.  Once you've done that, you have a mix of 
nodelists and arrays floating around; ideal APIs would not differentiate 
between the two.

> By the way, didn't you consider having several ways to achieve same result? For example, we could have both domList.toArray() and Array.import() methods simultaneously.

Having multiple APIs for the same thing is generally considered an 
antipattern, yes.

-Boris

Received on Friday, 23 December 2011 01:33:44 UTC