Files
smartstring/ts/smartstring.create.ts

88 lines
2.5 KiB
TypeScript
Raw Permalink Normal View History

2022-03-18 22:50:24 +01:00
import * as plugins from './smartstring.plugins.js';
2017-10-11 14:52:22 +02:00
/**
* Cross-platform random number generator
* Uses crypto.getRandomValues in browser and Math.random as fallback
*/
const getRandomInt = (min: number, max: number): number => {
if (typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.getRandomValues) {
// Browser environment with crypto API
const range = max - min;
const array = new Uint32Array(1);
globalThis.crypto.getRandomValues(array);
return min + (array[0] % range);
} else {
// Fallback to Math.random for environments without crypto
return Math.floor(Math.random() * (max - min)) + min;
}
};
/**
* Custom implementation of randomatic pattern-based string generator
* Pattern characters:
* A - Uppercase letter
* a - Lowercase letter
* 0 - Number (0-9)
* ! - Special character
* * - Any character (A, a, 0, or !)
*/
const customRandomatic = (pattern: string, length?: number, options?: any): string => {
const charSets = {
'A': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'a': 'abcdefghijklmnopqrstuvwxyz',
'0': '0123456789',
'!': '!@#$%^&*()_+-=[]{}|;:,.<>?',
'*': 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;:,.<>?'
};
// If length is provided, repeat the pattern to match length
let actualPattern = pattern;
if (length && length > pattern.length) {
actualPattern = pattern.repeat(Math.ceil(length / pattern.length)).slice(0, length);
} else if (length) {
actualPattern = pattern.slice(0, length);
}
let result = '';
for (const char of actualPattern) {
if (charSets[char]) {
const charSet = charSets[char];
const randomIndex = getRandomInt(0, charSet.length);
result += charSet[randomIndex];
} else {
// If not a pattern character, use it literally
result += char;
}
}
return result;
};
2019-01-12 20:12:58 +01:00
/**
* creates a random string
2019-04-16 08:55:37 +02:00
*
2019-01-12 20:12:58 +01:00
* ```ts
* createRandomString('AAAA')
2019-04-16 08:55:37 +02:00
* //=> 'AGHR'
2019-01-12 20:12:58 +01:00
* ```
2019-04-16 08:55:37 +02:00
*
2019-01-12 20:12:58 +01:00
* @param patternArg the pattern argument to use, Aa0!* are viable pattern descritors
* @param lengthArg the length of the random string
* @param optionsArg options
*/
2017-10-26 15:24:10 +02:00
export const createRandomString = (
2017-10-11 14:52:22 +02:00
patternArg: string,
2019-01-12 20:12:58 +01:00
lengthArg?: number,
optionsArg?: any
2017-10-11 14:52:22 +02:00
): string => {
return customRandomatic(patternArg, lengthArg, optionsArg);
};
2017-10-11 14:52:22 +02:00
2019-01-12 20:12:58 +01:00
/**
2020-12-31 04:42:46 +00:00
* creates a crytic string in the speicifed length
2019-01-12 20:12:58 +01:00
* @param lengthArg the length of the crypto string
*/
2022-03-18 22:50:24 +01:00
export const createCryptoRandomString = (): string => {
return plugins.isounique.uni();
};