diff options
| author | Leyla Jähnig <[email protected]> | 2023-01-09 19:59:37 +0100 |
|---|---|---|
| committer | GitHub <[email protected]> | 2023-01-09 19:59:37 +0100 |
| commit | 099e76ce0fb180beb5fd62d72a07c236e04cdca0 (patch) | |
| tree | a3b082a09579679ef371b0704e5b87f307cdaff5 /src/modules/string/index.ts | |
| parent | 27dff93aa27d755874aa5022c78f17ff8e9cf7e0 (diff) | |
| download | faker-099e76ce0fb180beb5fd62d72a07c236e04cdca0.tar.xz faker-099e76ce0fb180beb5fd62d72a07c236e04cdca0.zip | |
feat(string): nanoid (#1716)
Diffstat (limited to 'src/modules/string/index.ts')
| -rw-r--r-- | src/modules/string/index.ts | 42 |
1 files changed, 42 insertions, 0 deletions
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 @@ -533,6 +533,48 @@ export class StringModule { } /** + * 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. * * @param length Length of the generated string. Defaults to `1`. |
