Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created December 5, 2012 20:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwaldron/4219024 to your computer and use it in GitHub Desktop.
Save rwaldron/4219024 to your computer and use it in GitHub Desktop.
Collection Mutation Methods: benefits of return this

API calls, post-mutation

Set

Add value to the Set and...

...Get a fresh iterable for the keys, values, entries:

set.add( value ).keys();  
set.add( value ).values();
set.add( value ).entries();

...Send each value in the set to another operation:

set.add( value ).forEach( item => ...send to some operation.... );

...Spread into an array of unique items:

[ ...set.add(value) ]; // [ v, v, v, ... ]

Map

Add a key and value to the Map and...

...Get a fresh iterable for the keys, values, entries:

map.set( key, val ).keys();  
map.set( key, val ).values();
map.set( key, val ).entries();

...Send each to pair to another operation (see above)

map.set( key, val ).forEach( (key, val) => ...send to some operation.... );

...Spread into an array of pairs (see above)

[ ...map.set(value) ]; // [ [k,v], [k,v], ... ]

Argument Passing

// Imaginary library API...
System.processSet = function( set ) {
  ...
};

System.processMap = function( map ) {
  ...
};

// In my own program code:
System.processSet( set.add(newestValue) );

/* vs.

set.add(newestValue);
System.processSet( set );

*/

System.processSet( map.set(key, value) );

/* vs.

map.set(key, value);
System.processMap( map );
*/

Consequences of not returning this

Post-mutation operations:

( map.set(key, value), set ).keys();
( set.add(value), set ).values();
( set.add(value), set ).forEach( val => .... );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment