|
1 | | -import { int } from 'fictional' |
| 1 | +import { int, oneOf } from 'fictional' |
| 2 | +import { Input } from './types' |
2 | 3 |
|
3 | | -export const phoneNumber = (input: string) => |
4 | | - `+${int(input, { min: 10000000000, max: 999999999999999 })}` |
| 4 | +type PhoneNumberOptions = { |
| 5 | + /** |
| 6 | + * An array of prefixes to use when generating a phone number. |
| 7 | + * Can be used to generate a fictional phone number instead of a random one. |
| 8 | + * Using fictional phone numbers might make the generation slower. And might increase likelihood of collisions. |
| 9 | + * @example |
| 10 | + * ```ts |
| 11 | + * phoneNumber(seed, { |
| 12 | + * // Generate a French phone number within fictional phone number delimited range (cf: https://en.wikipedia.org/wiki/Fictitious_telephone_number) |
| 13 | + * prefixes: ['+3319900', '+3326191', '+3335301'], |
| 14 | + * // A french phone number is 11 digits long (including the prefix) so there is no need to generate a number longer than 4 digits |
| 15 | + * min: 1000, max: 9999 |
| 16 | + * }) |
| 17 | + * ``` |
| 18 | + * @example |
| 19 | + * |
| 20 | + * ```ts |
| 21 | + * phoneNumber(seed, { |
| 22 | + * // Generate a New Jersey fictional phone number |
| 23 | + * prefixes: ['+201555'], |
| 24 | + * min: 1000, max: 9999 |
| 25 | + * }) |
| 26 | + * ``` |
| 27 | + * @default undefined |
| 28 | + */ |
| 29 | + prefixes?: Array<string> |
| 30 | + /** |
| 31 | + * The minimum number to generate. |
| 32 | + * @default 10000000000 |
| 33 | + */ |
| 34 | + min?: number |
| 35 | + /** |
| 36 | + * The maximum number to generate. |
| 37 | + * @default 999999999999999 |
| 38 | + */ |
| 39 | + max?: number |
| 40 | +} |
| 41 | + |
| 42 | +export const phoneNumber = ( |
| 43 | + input: Input, |
| 44 | + options: PhoneNumberOptions = { min: 10000000000, max: 999999999999999 } |
| 45 | +) => { |
| 46 | + // Use provided min and max, or default values if not provided |
| 47 | + const min = options.min ?? 10000000000 |
| 48 | + const max = options.max ?? 999999999999999 |
| 49 | + |
| 50 | + if (options.prefixes) { |
| 51 | + const prefix = |
| 52 | + options.prefixes.length > 1 |
| 53 | + ? // If multiple prefixes are provided, pick one deterministically |
| 54 | + oneOf(input, options.prefixes) |
| 55 | + : options.prefixes[0] |
| 56 | + const prefixLength = prefix.length |
| 57 | + |
| 58 | + // Adjust min and max based on prefix length to keep a valid number of digits in the phone number |
| 59 | + const adjustedMin = Math.max(min, 10 ** (10 - prefixLength)) |
| 60 | + const adjustedMax = Math.min(max, 10 ** (15 - prefixLength) - 1) |
| 61 | + return `${prefix}${int(input, { |
| 62 | + min: adjustedMin, |
| 63 | + max: adjustedMax, |
| 64 | + })}` |
| 65 | + } |
| 66 | + |
| 67 | + return `+${int(input, { min, max })}` |
| 68 | +} |
0 commit comments