Skip to content

babiabeo/map-emplace

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

map-emplace

ci status codecov JSR JSR Score

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.

Install

Bun

bunx jsr add @polyfill/map-emplace

Deno

deno add @polyfill/map-emplace

or use import specifier:

import { emplaceMap } from "jsr:@polyfill/map-emplace";

Node

# npm
npx jsr add @polyfill/map-emplace

# yarn
yarn dlx jsr add @polyfill/map-emplace

# pnpm
pnpm dlx jsr add @polyfill/map-emplace

Why?

As mentioned in the proposal:

Adding and updating values of a Map are tasks that developers often perform in conjunction. There are currently no Map 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.

Examples

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;
    },
});

Insert if absent

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"...

Update if present

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";
    },
});

Specification

See also