Maps for emplace, TC39 proposal-upsert implementation.
deno:
deno add @miyauci/upsert
node:
npx jsr add @miyauci/upsert
Add a value to a map like if it does not already have something at key
, and
will also update an existing value at key
.
import { emplace } from "@miyauci/upsert";
import { assert } from "@std/assert";
declare const map: Map<string, number>;
declare const key: string;
const result = emplace(map, key, {
insert: () => 0,
update: (existing) => ++existing,
});
assert(map.has(key));
Add the entry if the key does not exist.
import { emplace } from "@miyauci/upsert";
import { assert } from "@std/assert";
import { assertType, type IsExact } from "@std/testing/types";
declare const map: Map<string, number>;
declare const key: string;
declare const value: number;
const result = emplace(map, key, { insert: () => value });
assert(map.has(key));
assertType<IsExact<typeof result, number>>(true);
If only inserting is required, insert
is available.
import { insert } from "@miyauci/upsert";
import { assertEquals } from "@std/assert";
declare const key: string;
declare const value: number;
const map = new Map<typeof key, typeof value>();
insert(map, key, () => value);
assertEquals(map, new Map([[key, value]]));
Update the entry if the key exists.
import { emplace } from "@miyauci/upsert";
import { assert } from "@std/assert";
import { assertType, type IsExact } from "@std/testing/types";
declare const map: Map<string, number>;
declare const key: string;
const result = emplace(map, key, { update: (existing) => ++existing });
assertType<IsExact<typeof result, number | undefined>>(true);
If only updating is required, update
is available.
import { update } from "@miyauci/upsert";
import { assertEquals } from "@std/assert";
declare const key: string;
const map = new Map([[key, 0]]);
update(map, key, (existing) => ++existing);
assertEquals(map, new Map([[key, 1]]));
Mixin for emplace
.
import { emplaceable } from "@miyauci/upsert";
import { assert } from "@std/assert";
class MyMap extends emplaceable(Map) {}
assert(MyMap.prototype.emplace);
Map
with Emplaceable implementation.
import { EmplaceableMap } from "@miyauci/upsert";
import { assert, assertInstanceOf } from "@std/assert";
const map = new EmplaceableMap<string, number>();
assertInstanceOf(map, Map);
assert(map.emplace);
WeakMap
with Emplaceable implementation.
import { EmplaceableWeakMap } from "@miyauci/upsert";
import { assert, assertInstanceOf } from "@std/assert";
const weakMap = new EmplaceableWeakMap();
assertInstanceOf(weakMap, WeakMap);
assert(weakMap.emplace);
Polyfill affects the global object. You must be very careful when using it.
import "@miyauci/upsert/polyfill";
import { assert } from "@std/assert";
assert(Map.prototype.emplace);
assert(WeakMap.prototype.emplace);
See jsr doc for all APIs.
See contributing.
MIT © 2023 Tomoki Miyauchi