Skip to main content
Module

x/memoization/deps.ts>emplace

Memoization tools, TC39 proposal-function-memo implementation
Latest
function emplace
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

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

Parameters

map: Readonly<MapLike<K, V>> & M
key: K
handler: Readonly<EmplaceHandler<K, V, M>>

Parameters

map: Readonly<MapLike<K, V>> & M
key: K
handler: Readonly<Insertable<K, V, M>>

Parameters

map: Readonly<MapLike<K, V>> & M
key: K
handler: Readonly<Updatable<K, V, M>>

Returns

V | undefined