| 11 | * @returns The decoded timestamp |
| 12 | */ |
| 13 | export function decodeTime(id: ULID): number { |
| 14 | if (id.length !== TIME_LEN + RANDOM_LEN) { |
| 15 | throw new ULIDError(ULIDErrorCode.DecodeTimeValueMalformed, "Malformed ULID"); |
| 16 | } |
| 17 | const time = id |
| 18 | .substr(0, TIME_LEN) |
| 19 | .toUpperCase() |
| 20 | .split("") |
| 21 | .reverse() |
| 22 | .reduce((carry, char, index) => { |
| 23 | const encodingIndex = ENCODING.indexOf(char); |
| 24 | if (encodingIndex === -1) { |
| 25 | throw new ULIDError( |
| 26 | ULIDErrorCode.DecodeTimeInvalidCharacter, |
| 27 | `Time decode error: Invalid character: ${char}` |
| 28 | ); |
| 29 | } |
| 30 | return (carry += encodingIndex * Math.pow(ENCODING_LEN, index)); |
| 31 | }, 0); |
| 32 | if (time > TIME_MAX) { |
| 33 | throw new ULIDError( |
| 34 | ULIDErrorCode.DecodeTimeValueMalformed, |
| 35 | `Malformed ULID: timestamp too large: ${time}` |
| 36 | ); |
| 37 | } |
| 38 | return time; |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Detect the best PRNG (pseudo-random number generator) |