Namespace: Random:randomUserCode

Random:randomUserCode

Source:

Methods

randomUserCode(alphabetopt, nullable, paddingCharacteropt, nullable, minLengthopt, nullable, maxLengthopt, nullable, randomValueopt, nullable) → {String}

Generates a random code, to be presented to the user, being easily readable and concise. Use this for things like, coupon codes, session IDs and everything, that might be transcribed by hand.

The algorithm used is using time-based information in combination with a larger random number, so, there should not be any collisions, but build in a fail-safe, if you persist this code to a database, to make absolutely sure, that the code is unique.

The used method here is formulated, to result in a short, concise highly readable code, while keeping the value highly random and as collision-free as possible. The basis for this is a combination of a compressed ISO-datetime string and a crypto-random-based combination of several random Uint8-values.

Hint: if you need a general implementation to convert a value to a certain alphabet/base, have a look at Conversion:toBaseX.

Parameters:
Name Type Attributes Default Description
alphabet String <optional>
<nullable>
'ACDEFGHKLMNPQRSTUVWXYZ2345679'

the character pool to use for code generation

paddingCharacter String <optional>
<nullable>
'8'

the character to use for value padding if generated code is too short

minLength Number <optional>
<nullable>
8

the min length, the code has to have at least, will be padded if too short

maxLength Number <optional>
<nullable>
12

the max length, the code can have at most, a code longer than this, will result in an error

randomValue Number <optional>
<nullable>
null

random integer to include in the code's base value, should be ~6 digits, will automatically be generated if missing

Source:
See:
Throws:
  • error if maxLength is smaller than minLength

  • error if the generated code is longer than maxLength

Returns:
the generated user code
Type
String
Example
randomUserCode()
=> 'GVK6RNQ8'
randomUserCode('0123456789ABCDEF', 10, 10, '=')
=> 'A03CF25D7='