Map.prototype.with

I'd like to be able to create a copy of a Map with a single value changed so instead of having to first clone the Map object and then calling Map.prototype.set, I'd like to be able to do this in one call.

const newMap = mapObject.with("a", 123);

This is particularly useful when using Maps in react state.

I guess this isn't so bad, but it wasn't obvious to me

const newMap = new Map(mapObject).set("a", 123);

It's not meant to be obvious, because it's a very poor-performing solution.

1 Like

or even new Map([...mapObject, ['a', 123]])

I suspect that would be slower, as it avoids any optimizations engines have for new Map(map) (if the iterator hasn't been patched)

2 Likes