diff options
| author | Amaan Shaikh <[email protected]> | 2024-10-31 15:30:16 +0530 |
|---|---|---|
| committer | GitHub <[email protected]> | 2024-10-31 10:00:16 +0000 |
| commit | 72937de55c892c011846bc2b67dc0df61fbdf5a2 (patch) | |
| tree | a14debb5d77f03f8a712f401b02544b06718e03f /src/modules/number/index.ts | |
| parent | c02beeadd49e48656a0307451517e9751e3118c3 (diff) | |
| download | faker-72937de55c892c011846bc2b67dc0df61fbdf5a2.tar.xz faker-72937de55c892c011846bc2b67dc0df61fbdf5a2.zip | |
feat(number): add romanNumeral method (#3070)
Diffstat (limited to 'src/modules/number/index.ts')
| -rw-r--r-- | src/modules/number/index.ts | 91 |
1 files changed, 91 insertions, 0 deletions
diff --git a/src/modules/number/index.ts b/src/modules/number/index.ts index be5e213f..f5f5c27f 100644 --- a/src/modules/number/index.ts +++ b/src/modules/number/index.ts @@ -443,4 +443,95 @@ export class NumberModule extends SimpleModuleBase { return min + offset; } + + /** + * Returns a roman numeral in String format. + * The bounds are inclusive. + * + * @param options Maximum value or options object. + * @param options.min Lower bound for generated roman numerals. Defaults to `1`. + * @param options.max Upper bound for generated roman numerals. Defaults to `3999`. + * + * @throws When `min` is greater than `max`. + * @throws When `min`, `max` is not a number. + * @throws When `min` is less than `1`. + * @throws When `max` is greater than `3999`. + * + * @example + * faker.number.romanNumeral() // "CMXCIII" + * faker.number.romanNumeral(5) // "III" + * faker.number.romanNumeral({ min: 10 }) // "XCIX" + * faker.number.romanNumeral({ max: 20 }) // "XVII" + * faker.number.romanNumeral({ min: 5, max: 10 }) // "VII" + * + * @since 9.2.0 + */ + romanNumeral( + options: + | number + | { + /** + * Lower bound for generated number. + * + * @default 1 + */ + min?: number; + /** + * Upper bound for generated number. + * + * @default 3999 + */ + max?: number; + } = {} + ): string { + const DEFAULT_MIN = 1; + const DEFAULT_MAX = 3999; + + if (typeof options === 'number') { + options = { + max: options, + }; + } + + const { min = DEFAULT_MIN, max = DEFAULT_MAX } = options; + + if (min < DEFAULT_MIN) { + throw new FakerError( + `Min value ${min} should be ${DEFAULT_MIN} or greater.` + ); + } + + if (max > DEFAULT_MAX) { + throw new FakerError( + `Max value ${max} should be ${DEFAULT_MAX} or less.` + ); + } + + let num = this.int({ min, max }); + + const lookup: Array<[string, number]> = [ + ['M', 1000], + ['CM', 900], + ['D', 500], + ['CD', 400], + ['C', 100], + ['XC', 90], + ['L', 50], + ['XL', 40], + ['X', 10], + ['IX', 9], + ['V', 5], + ['IV', 4], + ['I', 1], + ]; + + let result = ''; + + for (const [k, v] of lookup) { + result += k.repeat(Math.floor(num / v)); + num %= v; + } + + return result; + } } |
