Important
This package has been moved from
@babia/map-emplace
to
@polyfill/map-emplace
Polyfill of Map.prototype.emplace
and WeakMap.prototype.emplace
for
JavaScript based on
tc39/proposal-upsert
specification.
bunx jsr add @polyfill/map-emplace
deno add @polyfill/map-emplace
or use import specifier:
import { emplaceMap } from "jsr:@polyfill/map-emplace";
# npm
npx jsr add @polyfill/map-emplace
# yarn
yarn dlx jsr add @polyfill/map-emplace
# pnpm
pnpm dlx jsr add @polyfill/map-emplace
As mentioned in the proposal:
Adding and updating values of a
Map
are tasks that developers often perform in conjunction. There are currently noMap
prototype methods for either of those two things, let alone a method that does both. The workarounds involve multiple lookups and developer inconvenience while avoiding encouraging code that is surprising or is potentially error prone.
Therefore, emplace
method has been proposed as a solution for this problem.
emplaceMap(map, "foo", {
// If map does not include "foo", sets "foo" to 1
insert() {
return 1;
},
// Otherwise, updates its value.
update(oldValue) {
return oldValue + 2;
},
});
You might want to set a new value to a key if it does not exist in map, and then use that value in code:
if (!map.has("foo")) {
map.set("foo", "bar");
}
const foo = map.get("foo");
// do something with "foo"...
With emplace
:
const foo = emplaceMap(map, "foo", {
insert() {
return "bar";
},
});
// do something with "foo"...
You might want to update the value only if the key is exist:
if (map.has("foo")) {
map.set("foo", "foobar");
}
With emplace
:
emplaceMap(map, "foo", {
update() {
return "foobar";
},
});