New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
tabatkins opened this Issue Feb 4, 2019 · 4 comments

Comments

Projects
None yet
3 participants
@tabatkins
Copy link

tabatkins commented Feb 4, 2019

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

This comment has been minimized.

Copy link
Collaborator

Ginden commented Feb 5, 2019

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

This comment has been minimized.

Copy link
Member

ljharb commented Feb 5, 2019

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

This comment has been minimized.

@tabatkins

This comment has been minimized.

Copy link
Author

tabatkins commented Feb 6, 2019

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. ^_^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment