(now: number, len: number = TIME_LEN)
| 91 | * @returns The encoded time |
| 92 | */ |
| 93 | export function encodeTime(now: number, len: number = TIME_LEN): string { |
| 94 | if (isNaN(now)) { |
| 95 | throw new ULIDError( |
| 96 | ULIDErrorCode.EncodeTimeValueMalformed, |
| 97 | `Time must be a number: ${now}` |
| 98 | ); |
| 99 | } else if (now > TIME_MAX) { |
| 100 | throw new ULIDError( |
| 101 | ULIDErrorCode.EncodeTimeSizeExceeded, |
| 102 | `Cannot encode a time larger than ${TIME_MAX}: ${now}` |
| 103 | ); |
| 104 | } else if (now < 0) { |
| 105 | throw new ULIDError(ULIDErrorCode.EncodeTimeNegative, `Time must be positive: ${now}`); |
| 106 | } else if (Number.isInteger(now) === false) { |
| 107 | throw new ULIDError( |
| 108 | ULIDErrorCode.EncodeTimeValueMalformed, |
| 109 | `Time must be an integer: ${now}` |
| 110 | ); |
| 111 | } |
| 112 | let mod: number, |
| 113 | str: string = ""; |
| 114 | for (let currentLen = len; currentLen > 0; currentLen--) { |
| 115 | mod = now % ENCODING_LEN; |
| 116 | str = ENCODING.charAt(mod) + str; |
| 117 | now = (now - mod) / ENCODING_LEN; |
| 118 | } |
| 119 | return str; |
| 120 | } |
| 121 | |
| 122 | function inWebWorker(): boolean { |
| 123 | // @ts-ignore |
no outgoing calls
no test coverage detected