tc39 / proposal-collection-methods

https://tc39.github.io/proposal-collection-methods/
Other
172 stars 8 forks source link

Add `Map.update()`, combining `set` and `get`? #31

Closed tabatkins closed 5 years ago

tabatkins commented 5 years ago

Right now, if you want to update the value of a key in a map, you have to do a set/get dance and repeat yourself:

myMap.set(key, myMap.get(key)+1);

It might be worthwhile to combine these into one operation:

myMap.update(key, v=>v+1)

This is a little shorter, which is nice, but more importantly you don't repeat myMap and key, which is important if either of them are expressions rather than literals or variables. Because of the current repetition, the length savings also compound if either of those are long names. For example, the current way to increment an element's width in CSS Typed OM is:

el.attributeStyleMap.set('width', el.attributeStyleMap.get('width').add(CSS.px(5)))

which would shorten to

el.attributeStyleMap.update('width', w=>w.add(CSS.px(5)))

That feels like a significant usability improvement.

Ginden commented 5 years ago

That sounds like great addition. I'm not sure if (new Map).update("Foo", v => 1) should throw or create new entry.

How about update(key, fn, defaultValue)? This would be especially useful for grouping and counting.

ljharb commented 5 years ago

If we're going to have defaultValue, it should be a thunk, not a value, so that it can be lazily evaluated only if needed.

Ginden commented 5 years ago

https://tc39.github.io/proposal-collection-methods/#Map.prototype.update

tabatkins commented 5 years ago

That sounds like great addition. I'm not sure if (new Map).update("Foo", v => 1) should throw or create new entry.

How about update(key, fn, defaultValue)? This would be especially useful for grouping and counting.

I think it should create a new value, with the old value being undefined. And yeah, add a defaultValue thunk as well. ^_^