import { emplace } from "https://deno.land/x/memoization@1.2.0/deps.ts";
Add a value to a map if it does not already have something at key, and will also update an existing value at key.
Examples
Example 1
Example 1
import { emplace } from "https://deno.land/x/upsert@$VERSION/emplace.ts";
import { assert } from "https://deno.land/std/testing/asserts.ts";
declare const map: Map<string, number>;
declare const key: string;
const result = emplace(map, key, {
insert: () => 0,
update: (existing) => existing + 1,
});
assert(map.has(key));
Just insert if missing
You might omit an update
if you're handling data that doesn't change, but can
still be appended.
import { emplace } from "https://deno.land/x/upsert@$VERSION/emplace.ts";
import { assert } from "https://deno.land/std/testing/asserts.ts";
import {
assertType,
type IsExact,
} from "https://deno.land/std/testing/types.ts";
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);
Just update if present
You might want to omit an insert
if you want to perform a function on all
existing values.
import { emplace } from "https://deno.land/x/upsert@$VERSION/emplace.ts";
import { assert } from "https://deno.land/std/testing/asserts.ts";
import {
assertType,
type IsExact,
} from "https://deno.land/std/testing/types.ts";
declare const map: Map<string, number>;
declare const key: string;
const result = emplace(map, key, { update: (existing) => existing + 1 });
assertType<IsExact<typeof result, number | undefined>>(true);