Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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