Array subclassing, .map and iterables (Re: Jan 30 TC39 Meeting Notes)

Tab Atkins Jr. jackalmage at gmail.com
Sun Feb 10 12:04:34 PST 2013


On Sun, Feb 10, 2013 at 11:18 AM, Rick Waldron <waldron.rick at gmail.com> wrote:
> (Assuming a future where the DOM's NodeList inherits from Array)
>
> How would you produce a NodeList from an arbitrary array of strings?
>
>   NodeList.from( [ "div", "span", "p" ], nodeName =>
> document.createElement(nodeName) );
>
> Because...
>
>   NodeList.from( strings );
>
> Would try to make a NodeList, but with items that of a type that it
> disallows, meaning:
>
>   NodeList.from( strings ).map( nodeName => document.createElement(nodeName)
> );
>
> Would call .map() on an empty NodeList, since the string value items had
> been rejected. Of course, you might argue that I could just call it like:
>
>   NodeList.from( [ "div", "span", "p" ].map(nodeName =>
> document.createElement(nodeName)) );
>
> ...But the "arraylike" or "iterable" might not have a .map() method of its
> own, which will cause issues if I'm in a JS-target transpilation scenario...

>From what I've seen in the examples in this topic so far, it looks
like Array#from takes a second optional argument, which is a function
that you map the iterable elements through first, before giving them
to the constructor.  So, you would write:

NodeList.from( ["div", "span", "p"],
(nodeName)=>document.createElement(nodeName) );

~TJ


More information about the es-discuss mailing list