Skip to content

Instantly share code, notes, and snippets.

@Omkaragrawal
Last active April 21, 2022 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Omkaragrawal/5577d1548ceaf3c594fb7660a9563229 to your computer and use it in GitHub Desktop.
Save Omkaragrawal/5577d1548ceaf3c594fb7660a9563229 to your computer and use it in GitHub Desktop.
Use nanoid to generate random unique string. This function has lots of available formatting.
import { customAlphabet, nanoid } from 'nanoid';
import nanoidDictionary from 'nanoid-dictionary';
export enum NanoidStringEnum {
NUMERIC = 'NUMERIC',
LOWERCASE = 'LOWERCASE',
UPPERCASE = 'UPPERCASE',
ALPHABETS = 'ALPHABETS',
ALPHANUMERIC = 'ALPHANUMERIC',
LOWERCASE_NUMERIC = 'LOWERCASE_NUMERIC',
UPPERCASE_NUMERIC = 'UPPERCASE_NUMERIC',
// BuilderObject = 'BuilderObject',
CUSTOM = 'CUSTOM',
UUID = 'UUID',
}
type NanoidStringType = keyof typeof NanoidStringEnum;
/**
* Generate random string of supplied length using supplied set of characters.
* @param {NanoidStringType} [stringType="AlphaNumeric"] type of values that shall be included in the generated string, defaults to 'AlphaNumeric'.
* @param {number} [stringLength=10] Length of the string, default to 10.
* @param {string} custom to be entered only when stringType is "Custom" or "BuilderObject". When "Custom", characters in this string; and when "BuilderObject", this object; will be used to generate the string.
* @returns {string}
*/
public static generateRandomUniqueStringOfLength(
stringType: NanoidStringType = NanoidStringEnum.ALPHANUMERIC,
stringLength?: number,
custom?: string,
// custom?: string | Record<'includeNumeric' | 'includeLowercase' | 'includeUppercase' | 'includeHyphenAndUnderscore' | 'includeSpace' | 'includeDot', true | false>
): string {
let contentString = nanoidDictionary.alphanumeric;
if (stringType === NanoidStringEnum.NUMERIC) {
contentString = nanoidDictionary.numbers;
} else if (stringType === NanoidStringEnum.ALPHABETS) {
contentString = nanoidDictionary.lowercase + nanoidDictionary.uppercase;
} else if (stringType === NanoidStringEnum.LOWERCASE) {
contentString = nanoidDictionary.lowercase;
} else if (stringType === NanoidStringEnum.LOWERCASE_NUMERIC) {
contentString = nanoidDictionary.lowercase + nanoidDictionary.numbers;
} else if (stringType === NanoidStringEnum.UPPERCASE) {
contentString = nanoidDictionary.uppercase;
} else if (stringType === NanoidStringEnum.UPPERCASE_NUMERIC) {
contentString = nanoidDictionary.uppercase + nanoidDictionary.numbers;
}
// TODO: implement BuilderObject
/**
* else if (stringType === NanoidStringEnum.BuilderObject) {
* if (!this.isEmptyObject(custom as BuilderObjectType)) {
* contentString = '';
* if (custom.includeNumeric === true) {
* contentString += nanoidNumbers;
* }
* if (custom.includeLowercase === true) {
* contentString += nanoidLowercase;
* }
* if (custom.includeUppercase === true) {
* contentString += nanoidUppercase;
* }
* if (custom.includeHyphenAndUnderscore === true) {
* contentString += "-_";
* }
* if (custom.includeSpace === true) {
* contentString += " ";
* }
* if (custom.includeDot === true) {
* contentString += ".";
* }
* if (!!!contentString) {
* contentString = nanoidAlphanumeric;
* }
* }
* }
*/
else if (stringType === NanoidStringEnum.CUSTOM && _.isString(custom) && String(custom).length > 1) {
contentString = nanoidDictionary.lowercase + nanoidDictionary.uppercase;
} else {
contentString = nanoidDictionary.alphanumeric;
}
if (stringType === NanoidStringEnum.UUID) {
if (this.isNumber(String(stringLength))) {
nanoid(Number(stringLength));
}
return nanoid();
}
return customAlphabet(contentString, 10)(this.isNumber(String(stringLength)) ? Number(stringLength) : 10);
}
@Omkaragrawal
Copy link
Author

  public static random(min: number, max: number): number {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  public static uniqueString(): string {
    return EncodeBase62(Number.parseInt(`${Utils.random(1111, 9999)}${Date.now()}`));
  }

  public static uniqueId(): number {
    return Number.parseInt(`${Date.now()}${Utils.random(111, 999)}`);
  }

As Opposed to this.

@Omkaragrawal
Copy link
Author

import { customAlphabet, nanoid } from 'nanoid';
//import nanoidDictionary from 'nanoid-dictionary';

const nanoidDictionary = {
	uppercase: "",
	lowercase: "",
	numbers: "",
	alphanumeric: ""
}

export enum NanoidStringEnum {
	NUMERIC = 'NUMERIC',
	LOWERCASE = 'LOWERCASE',
	UPPERCASE = 'UPPERCASE',
	ALPHABETS = 'ALPHABETS',
	ALPHANUMERIC = 'ALPHANUMERIC',
	LOWERCASE_NUMERIC = 'LOWERCASE_NUMERIC',
	UPPERCASE_NUMERIC = 'UPPERCASE_NUMERIC',
	UUID = 'UUID',
}

export class generateRandomUniqueStringOfLengthConfig {
	numeric?: boolean;
	lowercase?: boolean;
	uppercase?: boolean;
	hyphenAndUnderscore?: boolean;
	space?: boolean;
	dot?: boolean;
	characters?: string;
}

/**
 * Generate random string of supplied length using supplied set of characters.
 * @param  {NanoidStringEnum} [typeOrConfig="ALPHANUMERIC"] type of values that shall be included in the generated string, defaults to 'AlphaNumeric'.
 * @param  {number} [stringLength=10] Length of the string, default to 10.
 * @param  {string} custom to be entered only when stringType is "Custom" or "BuilderObject". When "Custom", characters in this string; and when "BuilderObject", this object; will be used to generate the string.
 * @returns {string}
*/
function generateRandomUniqueStringOfLength(
	typeOrConfig: generateRandomUniqueStringOfLengthConfig | NanoidStringEnum = NanoidStringEnum.ALPHANUMERIC,
	stringLength: number = 10,
): string {
	if (typeOrConfig == NanoidStringEnum.UUID)
		return nanoid(stringLength);

	let config: generateRandomUniqueStringOfLengthConfig = {};
	if (typeof typeOrConfig == "object")
		config = typeOrConfig;
	else
		switch (typeOrConfig) {
			case NanoidStringEnum.NUMERIC:
				config.numeric = true;
				break;

			case NanoidStringEnum.ALPHABETS:
				config.uppercase = true;
				config.lowercase = true;
				break;

			case NanoidStringEnum.LOWERCASE:
				config.lowercase = true;
				break;

			case NanoidStringEnum.LOWERCASE_NUMERIC:
				config.lowercase = true;
				config.numeric = true;
				break;

			case NanoidStringEnum.UPPERCASE:
				config.uppercase = true;
				break;

			case NanoidStringEnum.UPPERCASE_NUMERIC:
				config.uppercase = true;
				config.numeric = true;
				break;

			case NanoidStringEnum.ALPHABETS:
				config.lowercase = true;
				config.uppercase = true;
				break;

			case NanoidStringEnum.ALPHANUMERIC:
				config.lowercase = true;
				config.uppercase = true;
				config.numeric = true;
				break;
		}

	let alphabet = "";
	if (config.numeric)
		alphabet += nanoidDictionary.numbers;
	if (config.lowercase)
		alphabet += nanoidDictionary.lowercase;
	if (config.uppercase)
		alphabet += nanoidDictionary.uppercase;
	if (config.hyphenAndUnderscore)
		alphabet += "-_";
	if (config.space)
		alphabet += " ";
	if (config.dot)
		alphabet += ".";
	if (config.characters)
		alphabet += config.characters;

	return customAlphabet(alphabet)(stringLength);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment