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/modules/string | |
| parent | 2f93d9da383638b6d232ff8b3cae827ea4c80150 (diff) | |
| download | faker-5b1c8588f8a57be712e64434f7b17a8407a4f465.tar.xz faker-5b1c8588f8a57be712e64434f7b17a8407a4f465.zip | |
feat(string): adds support for generating ULID (#2524)
Diffstat (limited to 'src/modules/string')
| -rw-r--r-- | src/modules/string/index.ts | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/src/modules/string/index.ts b/src/modules/string/index.ts index 7df31fc7..67073242 100644 --- a/src/modules/string/index.ts +++ b/src/modules/string/index.ts @@ -1,4 +1,6 @@ import { FakerError } from '../../errors/faker-error'; +import { CROCKFORDS_BASE32, dateToBase32 } from '../../internal/base32'; +import { toDate } from '../../internal/date'; import { SimpleModuleBase } from '../../internal/module-base'; import type { LiteralUnion } from '../../internal/types'; @@ -705,6 +707,37 @@ export class StringModule extends SimpleModuleBase { } /** + * Returns a ULID ([Universally Unique Lexicographically Sortable Identifier](https://github.com/ulid/spec)). + * + * @param options The optional options object. + * @param options.refDate The timestamp to encode into the ULID. + * The encoded timestamp is represented by the first 10 characters of the result. + * Defaults to `faker.defaultRefDate()`. + * + * @example + * faker.string.ulid() // '01ARZ3NDEKTSV4RRFFQ69G5FAV' + * faker.string.ulid({ refDate: '2020-01-01T00:00:00.000Z' }) // '01DXF6DT00CX9QNNW7PNXQ3YR8' + * + * @since 9.1.0 + */ + ulid( + options: { + /** + * The date to use as reference point for the newly generated ULID encoded timestamp. + * The encoded timestamp is represented by the first 10 characters of the result. + * + * @default faker.defaultRefDate() + */ + refDate?: string | Date | number; + } = {} + ): string { + const { refDate = this.faker.defaultRefDate() } = options; + const date = toDate(refDate); + + return dateToBase32(date) + this.fromCharacters(CROCKFORDS_BASE32, 16); + } + + /** * Generates a [Nano ID](https://github.com/ai/nanoid). * * @param length Length of the generated string. Defaults to `21`. |
