Why does Array.from also take a mapFn?

Rick Waldron waldron.rick at gmail.com
Mon Jun 24 10:01:04 PDT 2013


On Mon, Jun 24, 2013 at 12:42 PM, Domenic Denicola <
domenic at domenicdenicola.com> wrote:

> From: Allen Wirfs-Brock [allen at wirfs-brock.com]
>
> > My recollection is that we first discussed that the existence of
> Array.from make this issue somewhat less important because, just as you
> point out, .from can be used in conjunction with anything that produces an
> Iterable such as V.from(v.map(val => val * 2))
>
> > That led to further discision of that usage and we got into things like
> the last example:
> >
> > ```js
> > // Turn an array of nodeNames into NodeList of nodes
> > NodeList.from( ["div"], node => document.createElement(node) );
> > ```
>
> I think I must be missing something. Why is this superior to
>
> ```js
> NodeList.from(["div"].map(node => document.createElement(node));
> ```
>
> which you gave as an example just a few lines above? In other words, why
> does `Array.from` accept a second parameter at all?
>

One reason is the extra allocation...

given:
  let nodeNames = ["div", "span"];

  NodeList.from(nodeNames.map(node => document.createElement(node)));

This example is going to produce an extra array (the result of .map())
before it even gets passed into the NodeList.from() call, which will then
create a NodeList and then populate it with items from iterable argument.

  NodeList.from(["div"], node => document.createElement(node));

This will not create the extra array, only the NodeList.



> Another question that I don't think got an answer, or if it did I was
> unable to understand it. Why is "map" singled out for `Array.from` instead
> of, say, "filter"? It seems arbitrary.
>

It's not at all arbitrary: filter isn't an operation used to change the
value of the items in the returned iterable.


Rick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130624/c9a32a2b/attachment-0001.html>


More information about the es-discuss mailing list