diff options
| author | Bruno Leite <[email protected]> | 2024-10-10 13:08:57 -0300 |
|---|---|---|
| committer | GitHub <[email protected]> | 2024-10-10 18:08:57 +0200 |
| commit | 5b1c8588f8a57be712e64434f7b17a8407a4f465 (patch) | |
| tree | 0e59657cb03f9827b7165bbfc3053ec4867a1016 /src/internal | |
| parent | 2f93d9da383638b6d232ff8b3cae827ea4c80150 (diff) | |
| download | faker-5b1c8588f8a57be712e64434f7b17a8407a4f465.tar.xz faker-5b1c8588f8a57be712e64434f7b17a8407a4f465.zip | |
feat(string): adds support for generating ULID (#2524)
Diffstat (limited to 'src/internal')
| -rw-r--r-- | src/internal/base32.ts | 21 | ||||
| -rw-r--r-- | src/internal/date.ts | 22 |
2 files changed, 43 insertions, 0 deletions
diff --git a/src/internal/base32.ts b/src/internal/base32.ts new file mode 100644 index 00000000..f3e15bb4 --- /dev/null +++ b/src/internal/base32.ts @@ -0,0 +1,21 @@ +/** + * Crockford's Base32 - Excludes I, L, O, and U which may be confused with numbers + */ +export const CROCKFORDS_BASE32 = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; + +/** + * Encodes a Date into 10 characters base32 string. + * + * @param date The Date to encode. + */ +export function dateToBase32(date: Date): string { + let value = date.valueOf(); + let result = ''; + for (let len = 10; len > 0; len--) { + const mod = value % 32; + result = CROCKFORDS_BASE32[mod] + result; + value = (value - mod) / 32; + } + + return result; +} diff --git a/src/internal/date.ts b/src/internal/date.ts new file mode 100644 index 00000000..40751c2d --- /dev/null +++ b/src/internal/date.ts @@ -0,0 +1,22 @@ +import { FakerError } from '../errors/faker-error'; + +/** + * Converts a date passed as a `string`, `number` or `Date` to a valid `Date` object. + * + * @param date The date to convert. + * @param name The reference name used for error messages. Defaults to `'refDate'`. + * + * @throws If the given date is invalid. + */ +export function toDate( + date: string | Date | number, + name: string = 'refDate' +): Date { + const converted = new Date(date); + + if (Number.isNaN(converted.valueOf())) { + throw new FakerError(`Invalid ${name} date: ${date.toString()}`); + } + + return converted; +} |
