Open dminor opened 1 month ago
There was a previous conversation (see https://github.com/tc39/proposal-upsert/issues/29) about naming for the original design of this proposal.
In Dart this is called putIfAbsent()
, although setIfAbsent()
might be a better fit given Map.set()
.
cc a few people whom I recall expressing an opinion on the naming at plenary: @ljharb @rkirsling @acutmore @rbuckton @bakkot @syg
I don't like setIfAbsent
because it emphasizes the action of inserting, whereas the primary use for this is fetching an existing value.
getOrInsert
is good, but I don't love getOrInsertComputed
. Nothing better comes to mind, though.
Both current names LGTM - definitely better than was before since they perfectly describe their logic.
+1 to prefixing with get...
. To add further rationale, Map.prototype.set
returns the map instance, not the inserted value.
I might be inclined to suggest getWithDefault
, since the one issue with getOrInsert
is that we want to get
either way, we just might need to insert
first.
I suppose this would also allow us to rearrange ...Computed
into getWithComputedDefault
.
I suspect some may interpret getWithDefault
as a method that never mutates the map - the method form of map.get(key) ?? defaultV
.
I might be inclined to suggest
getWithDefault
, since the one issue withgetOrInsert
is that we want toget
either way, we just might need toinsert
first.
You can look at it that way, but you can also look at as the insert
case just returning the inserted value.
Just to throw out an extreme alternative, insertIfMissingThenGet
(I’m not actually suggesting we do this one, ofc)
How about something as simple as upsert
itself?
This was suggested in a comment from the original thread here.
I think there is a good reason the proposal itself is called upsert
😁
The API no longer has the "update" aspect. Only lazy initialisation. Making the name "upsert" less applicable than at the start.
The proposal would add two new methods to Map:
getOrInsert(key, default)
- Return value corresponding to the key if present, otherwise insert the specified default value and return that.getOrInsertComputed(key, callback)
- Return value corresponding to the key if present, otherwise call the callback function to determine the default value to insert and return.Those names are placeholders, I'm opening this issue so we can bikeshed the final names to be used.