From 099e76ce0fb180beb5fd62d72a07c236e04cdca0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leyla=20J=C3=A4hnig?= Date: Mon, 9 Jan 2023 19:59:37 +0100 Subject: feat(string): nanoid (#1716) --- src/modules/string/index.ts | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) (limited to 'src') diff --git a/src/modules/string/index.ts b/src/modules/string/index.ts index 85d29b9d..d48f4542 100644 --- a/src/modules/string/index.ts +++ b/src/modules/string/index.ts @@ -532,6 +532,48 @@ export class StringModule { return RFC4122_TEMPLATE.replace(/[xy]/g, replacePlaceholders); } + /** + * Generates a [Nano ID](https://github.com/ai/nanoid). + * + * @param length Length of the generated string. Defaults to `21`. + * @param length.min The minimum length of the Nano ID to generate. + * @param length.max The maximum length of the Nano ID to generate. + * + * @example + * faker.string.nanoid() // ptL0KpX_yRMI98JFr6B3n + * faker.string.nanoid(10) // VsvwSdm_Am + * faker.string.nanoid({ min: 13, max: 37 }) // KIRsdEL9jxVgqhBDlm + * + * @since 8.0.0 + */ + nanoid(length: number | { min: number; max: number } = 21): string { + length = this.faker.helpers.rangeToNumber(length); + if (length <= 0) { + return ''; + } + + const generators = [ + { + value: () => this.alphanumeric(1), + // a-z is 26 characters + // this times 2 for upper & lower case is 52 + // add all numbers 0-9 (10 in total) you get 62 + weight: 62, + }, + { + value: () => this.faker.helpers.arrayElement(['_', '-']), + weight: 2, + }, + ]; + let result = ''; + while (result.length < length) { + const charGen = this.faker.helpers.weightedArrayElement(generators); + result += charGen(); + } + + return result; + } + /** * Returns a string containing only special characters. * -- cgit v1.2.3