* Generates a [Nano ID](https://github.com/ai/nanoid). * * @param length The length of the string to generate either as a fixed length or as a length range. Defaults to `21`. * @param length.min The minimum length of the Nano ID to generate. * @param length.max The maximum length of the
(
length:
| number
| {
/**
* The minimum length of the Nano ID to generate.
*/
min: number;
/**
* The maximum length of the Nano ID to generate.
*/
max: number;
} = 21
)
| 839 | * @since 8.0.0 |
| 840 | */ |
| 841 | nanoid( |
| 842 | length: |
| 843 | | number |
| 844 | | { |
| 845 | /** |
| 846 | * The minimum length of the Nano ID to generate. |
| 847 | */ |
| 848 | min: number; |
| 849 | /** |
| 850 | * The maximum length of the Nano ID to generate. |
| 851 | */ |
| 852 | max: number; |
| 853 | } = 21 |
| 854 | ): string { |
| 855 | length = this.faker.helpers.rangeToNumber(length); |
| 856 | if (length <= 0) { |
| 857 | return ''; |
| 858 | } |
| 859 | |
| 860 | const generators = [ |
| 861 | { |
| 862 | value: () => this.alphanumeric(1), |
| 863 | // a-z is 26 characters |
| 864 | // this times 2 for upper & lower case is 52 |
| 865 | // add all numbers 0-9 (10 in total) you get 62 |
| 866 | weight: 62, |
| 867 | }, |
| 868 | { |
| 869 | value: () => this.faker.helpers.arrayElement(['_', '-']), |
| 870 | weight: 2, |
| 871 | }, |
| 872 | ]; |
| 873 | let result = ''; |
| 874 | while (result.length < length) { |
| 875 | const charGen = this.faker.helpers.weightedArrayElement(generators); |
| 876 | result += charGen(); |
| 877 | } |
| 878 | |
| 879 | return result; |
| 880 | } |
| 881 | |
| 882 | /** |
| 883 | * Returns a string containing only special characters from the following list: |
no test coverage detected