Line data Source code
1 : import { StringDistribution } from "../types.ts"; 2 1 : import { integer } from "./integer.ts"; 3 : 4 : // tslint:disable:unified-signatures 5 : 6 : // has 2**x chars, for faster uniform distribution 7 1 : const DEFAULT_STRING_POOL = 8 1 : "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"; 9 : 10 : /** 11 : * Returns a distribution that returns a random string using numbers, 12 : * uppercase and lowercase letters, `_`, and `-` of length `length`. 13 : * @param length Length of the result string 14 : */ 15 : export function string(): StringDistribution; 16 : /** 17 : * Returns a distribution that returns a random string using the provided 18 : * string pool as the possible characters to choose from of length `length`. 19 : * @param length Length of the result string 20 : */ 21 : export function string(pool: string): StringDistribution; 22 1 : export function string(pool: string = DEFAULT_STRING_POOL): StringDistribution { 23 3 : const poolLength = pool.length; 24 0 : if (!poolLength) { 25 0 : throw new Error("Expected pool not to be an empty string"); 26 0 : } 27 : 28 3 : const distribution = integer(0, poolLength - 1); 29 0 : return (engine, length) => { 30 0 : let result = ""; 31 0 : for (let i = 0; i < length; ++i) { 32 0 : const j = distribution(engine); 33 0 : result += pool.charAt(j); 34 0 : } 35 0 : return result; 36 0 : }; 37 1 : }