aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/modules/string/index.ts42
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`.