From 5b1c8588f8a57be712e64434f7b17a8407a4f465 Mon Sep 17 00:00:00 2001 From: Bruno Leite Date: Thu, 10 Oct 2024 13:08:57 -0300 Subject: feat(string): adds support for generating ULID (#2524) --- src/modules/string/index.ts | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) (limited to 'src/modules/string') 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'; @@ -704,6 +706,37 @@ export class StringModule extends SimpleModuleBase { .replaceAll('y', () => this.faker.number.hex({ min: 0x8, max: 0xb })); } + /** + * 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). * -- cgit v1.2.3