Array subclassing, .map and iterables (Re: Jan 30 TC39 Meeting Notes)
Erik Arvidsson
erik.arvidsson at gmail.com
Sat Feb 9 09:34:45 PST 2013
One of the problems with map is that the return type of the function
might be different. With some pseudo syntax for types
function f(x : T) : V { ... }
var a : Array.<T> = ...
var b = a.map(f);
b is actually of type Array.<V> and not of Array.<T>
This becomes an issue with typed arrays at least.
On Sat, Feb 9, 2013 at 5:16 AM, Claus Reinke <claus.reinke at talk21.com> wrote:
> I am trying to understand the discussion and resolution of
> 'The Array Subclassing "Kind" Issue'. The issue (though not its
> solution) seemed simple enough
>
> class V extends Array { ... }
> m = (new V()).map(val => val);
> console.log( m instanceof V ); // false :(
>
> and I was expecting solutions somewhere along this path:
>
> 1. .map should work for Array subclasses, preserving class
>
> 2. .map is independent of Array and its subclasses, there are
> lots of types for which it makes sense (Sets, EventEmitters, ..)
>
> 3. there should be an interface Mapable, implemented by
> Array and its subclasses, but also by other relevant classes,
> such that
>
> class M implements Mapable { ... }
> m = (new M()).map(val => val);
> console.log( m instanceof M ); // true
>
> (in typed variants of JS, this would call for generics, to separate
> structure class -supporting map- from element class -being mapped)
>
> Instead, the accepted approach -if I understood it correctly-
> focuses on conversion and iterables:
>
> Array.from( iterable ) => Array.from( iterable, mapFn )
>
> such that
>
> SubArray.from( iterable, val => val ) instanceof SubArray
>
> This seems very odd to me, because
>
> - it introduces a second form of .map, in .from
>
> - instead of limiting to Array, .from-map is now limited to iterables
> (it would work for Set, which is really OrderedSet, but it wouldn't
> work for WeakMap)
>
> - it doesn't address the general problem: how to inherit structural
> functionality (such as mapping over all elements or a container/
> iterable) while preserving class
>
> With a general solution to the issue, I would expect to write
>
> SubArray.from( iterable ).map( val => val ) instanceof SubArray
>
> while also getting
>
> new Mapable().map( val => val ) instanceof Mapable
>
> Could someone please elaborate why the committee went with an additional map
> built into structure conversion instead?
>
> Claus
>
> PS. What about array comprehensions and generator expressions?
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
--
erik
More information about the es-discuss
mailing list