Skip to main content
Home
This release is 1 version behind 0.0.5 — the latest version of @thai/get-or-create. Jump to latest

Built and signed on GitHub Actions

Convenience function to get or create a value in a map

This package works with Cloudflare Workers, Node.js, Deno, Bun, Browsers
This package works with Cloudflare Workers
This package works with Node.js
This package works with Deno
This package works with Bun
This package works with Browsers
JSR Score
100%
Published
2 years ago (0.0.4)

The @thai/get-or-create package provides the getOrCreate function that can be used to get or create a value in a map.

Usage

import { getOrCreate } from "@thai/get-or-create";

// Let's calculate a tally for each word in this array.
const words = ["one", "two", "three", "one"];

// We'll use a map to store the tally.
const tally = new Map<string, { count: number }>();

// We can use the `getOrCreate` function to get or create
// the counter object for each word.
for (const word of words) {
  getOrCreate(tally, word, () => ({ count: 0 })).count++;
}

// The tally map now contains the count for each word:
//
// Map(3) {
//   'one' => { count: 2 },
//   'two' => { count: 1 },
//   'three' => { count: 1 }
// }

It can also be used with a WeakMap to implement a memoization cache.

Built and signed on
GitHub Actions

New Ticket: Report package

Please provide a reason for reporting this package. We will review your report and take appropriate action.

Please review the JSR usage policy before submitting a report.

Add Package

deno add jsr:@thai/get-or-create

Import symbol

import * as get_or_create from "@thai/get-or-create";
or

Import directly with a jsr specifier

import * as get_or_create from "jsr:@thai/get-or-create";

Add Package

pnpm i jsr:@thai/get-or-create
or (using pnpm 10.8 or older)
pnpm dlx jsr add @thai/get-or-create

Import symbol

import * as get_or_create from "@thai/get-or-create";

Add Package

yarn add jsr:@thai/get-or-create
or (using Yarn 4.8 or older)
yarn dlx jsr add @thai/get-or-create

Import symbol

import * as get_or_create from "@thai/get-or-create";

Add Package

vlt install jsr:@thai/get-or-create

Import symbol

import * as get_or_create from "@thai/get-or-create";

Add Package

npx jsr add @thai/get-or-create

Import symbol

import * as get_or_create from "@thai/get-or-create";

Add Package

bunx jsr add @thai/get-or-create

Import symbol

import * as get_or_create from "@thai/get-or-create";