Map: filter/map and more

Tab Atkins Jr. jackalmage at gmail.com
Thu Nov 20 10:39:39 PST 2014


On Thu, Nov 20, 2014 at 10:32 AM, Axel Rauschmayer <axel at rauschma.de> wrote:
> At the meeting it was decided not to go with `map` and `filter` sitting on
> `Map.prototype`, but instead to use iterators in the way like:
>
> ```
> map
>   .entries() // returns an iterator
>   .map((v, k, m) => { ... })
>   .filter((v, k, m) => { ... })
>   .collect(); // returns a new map after all transforms
> ```
>
>
> Convenient, but this pattern couldn’t be extended to new Map classes or
> other collections. I see two alternatives.
>
> First, use the `Map` constructor. I don’t find this too bad and it’s
> self-explanatory.
>
> ```js
> new Map(map
>   .entries() // returns an iterator
>   .map((v, k, m) => { ... })
>   .filter((v, k, m) => { ... }));
> ```
>
> Second:
>
> ```js
> map
>   .entries() // returns an iterator
>   .map((v, k, m) => { ... })
>   .filter((v, k, m) => { ... })
>   .collectInto(new Map());
> ```
>
> `collectInto(coll)` invokes `coll.set(k,v)` for each pair `[k,v]` in the
> sequence. It returns `coll`.

+1.  This also gives us a pseudonym for Python's .update() operation,
which adds one dict into another, and which I use relatively often to
merge dictionaries together.  Where Python would say `m1.update(m2)`
(m1 now contains all of m2's data), JS would say
`m2.entries().collectInto(m1)`.

This is more powerful than just using the constructor, as it allows
you to update a dict that already has information in it, and adding
another function to a chain of transformations is slightly easier to
do than wrapping it in a function call.

~TJ


More information about the es-discuss mailing list