proposal-emitter icon indicating copy to clipboard operation
proposal-emitter copied to clipboard

Collection Helpers

Open pemrouz opened this issue 5 years ago • 0 comments

reduce is the operator that is responsible for serialising new collections, and there's a shorthand generalisation that makes it more ergonomic i.e. reduce([]) to collect into an array, reduce({}) to collect into an object, etc. Currently it knows about a limited set of types, but was also planning to make it a Symbol-based protocol. The prototype just needs one Symbol that dictates how to concat new values it receives into itself.

With Emitter we can tease apart the three concerns of "iteration, transformation, and accumulation". Here's a snippet from one of the tests that explores the entire matrix of going from/to Array, Object, String, Number, Function, Generator, Async Generator, Emitter with a series of transformations in between.

@gsathya, here's what I was thinking re: collection helpers proposal. We can spec it in a generic way to work with all collections rather than duplicating functionality:

Map.prototype.map = function(fn){ return run(this, map(fn), reduce(new this.constructor) ) }
Set.prototype.map = function(fn){ return run(this, map(fn), reduce(new this.constructor) ) }

That is, each of the collection helper methods apply the corresponding transform and serialise the values into a new collection of the same type.

(Note: new this.constructor can also be new this.constructor[Symbol.species], but @syg has more thoughts on that).

pemrouz avatar Jul 23 '19 05:07 pemrouz