Skip to main content

Polyfill of `emplace` method for JavaScript

Works with
This package works with Bun
This package works with Cloudflare Workers
This package works with Node.js
This package works with Deno
It is unknown whether this package works with Browsers
JSR Score
100%
Published
4 weeks ago (0.1.0)

Polyfill of Map.prototype.emplace and WeakMap.prototype.emplace for JavaScript which have been proposed in https://github.com/tc39/proposal-upsert.

Examples

emplaceMap

const map = new Map([["foo", 9]]);

emplaceMap(map, "foo", {
    insert() {
        return 7;
    },
    update(oldValue) {
        return oldValue * 3;
    },
});

emplaceMap(map, "bar", {
    insert() {
        return 7;
    },
    update(oldValue) {
        return oldValue * 3;
    },
});

console.log(map); // Map(2) { "foo": 27, "bar": 7 }

emplaceWeakMap

const map = new WeakMap<WeakKey, number>();
const o1 = {};
const o2 = function () {};

map.set(o1, 21);

emplaceWeakMap(map, o1, {
    insert() {
        return 100;
    },
    update(oldValue) {
        return oldValue + 50;
    },
});

emplaceWeakMap(map, o2, {
    insert() {
        return 100;
    },
    update(oldValue) {
        return oldValue + 50;
    },
});

console.log(map.get(o1)); // 71
console.log(map.get(o2)); // 100
Built and signed on
GitHub Actions
View transparency log

Add Package

deno add @polyfill/map-emplace

Import symbol

import * as mod from "@polyfill/map-emplace";

Add Package

npx jsr add @polyfill/map-emplace

Import symbol

import * as mod from "@polyfill/map-emplace";

Add Package

yarn dlx jsr add @polyfill/map-emplace

Import symbol

import * as mod from "@polyfill/map-emplace";

Add Package

pnpm dlx jsr add @polyfill/map-emplace

Import symbol

import * as mod from "@polyfill/map-emplace";

Add Package

bunx jsr add @polyfill/map-emplace

Import symbol

import * as mod from "@polyfill/map-emplace";