From 8353169d9df7abf35793ae7fc78fe468318cf95d Mon Sep 17 00:00:00 2001 From: Ryan Atkinson Date: Thu, 16 Nov 2023 10:57:16 -0700 Subject: [PATCH] add `random_char` helper --- .changeset/eight-bottles-dress.md | 5 +++++ src/lib/package.ts | 1 + src/lib/random.ts | 5 +++++ 3 files changed, 11 insertions(+) create mode 100644 .changeset/eight-bottles-dress.md diff --git a/.changeset/eight-bottles-dress.md b/.changeset/eight-bottles-dress.md new file mode 100644 index 00000000..8d95727b --- /dev/null +++ b/.changeset/eight-bottles-dress.md @@ -0,0 +1,5 @@ +--- +'@grogarden/util': patch +--- + +add `random_char` helper diff --git a/src/lib/package.ts b/src/lib/package.ts index 7d2cfb68..fbea188d 100644 --- a/src/lib/package.ts +++ b/src/lib/package.ts @@ -286,6 +286,7 @@ export const src_json = { {name: 'random_int', kind: 'function'}, {name: 'random_boolean', kind: 'function'}, {name: 'random_item', kind: 'function'}, + {name: 'random_char', kind: 'function'}, {name: 'shuffle', kind: 'function'}, ], }, diff --git a/src/lib/random.ts b/src/lib/random.ts index f09abd66..41bd8ffc 100644 --- a/src/lib/random.ts +++ b/src/lib/random.ts @@ -9,6 +9,11 @@ export const random_boolean = (random = Math.random): boolean => random() > 0.5; export const random_item = (arr: T[], random = Math.random): T => arr[random_int(0, arr.length - 1, random)]; +export const random_char = (chars = alphanumerics, random = Math.random): string => + random_item(chars, random); + +const alphanumerics = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.split(''); + /** * Mutates `array` with random ordering. */