|
| 1 | +import type { FakerCore } from '../../faker-core'; |
| 2 | +import { numeric } from '../string/numeric'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Returns a random flight number. Flight numbers are always 1 to 4 digits long. Sometimes they are |
| 6 | + * used without leading zeros (e.g.: `American Airlines flight 425`) and sometimes with leading |
| 7 | + * zeros, often with the airline code prepended (e.g.: `AA0425`). |
| 8 | + * |
| 9 | + * To generate a flight number prepended with an airline code, combine this function with the |
| 10 | + * `airline()` function and use template literals: |
| 11 | + * ``` |
| 12 | + * `${airline(fakerCore).iataCode}${flightNumber(fakerCore, { addLeadingZeros: true })}` // 'AA0798' |
| 13 | + * ``` |
| 14 | + * |
| 15 | + * @param fakerCore The FakerCore to use. |
| 16 | + * @param options The options to use. |
| 17 | + * @param options.length The number or range of digits to generate. Defaults to `{ min: 1, max: 4 }`. |
| 18 | + * @param options.addLeadingZeros Whether to pad the flight number up to 4 digits with leading zeros. Defaults to `false`. |
| 19 | + * |
| 20 | + * @example |
| 21 | + * flightNumber(fakerCore) // '2405' |
| 22 | + * flightNumber(fakerCore, { addLeadingZeros: true }) // '0249' |
| 23 | + * flightNumber(fakerCore, { addLeadingZeros: true, length: 2 }) // '0042' |
| 24 | + * flightNumber(fakerCore, { addLeadingZeros: true, length: { min: 2, max: 3 } }) // '0624' |
| 25 | + * flightNumber(fakerCore, { length: 3 }) // '425' |
| 26 | + * flightNumber(fakerCore, { length: { min: 2, max: 3 } }) // '84' |
| 27 | + * |
| 28 | + * @since 8.0.0 |
| 29 | + */ |
| 30 | +export function flightNumber( |
| 31 | + fakerCore: FakerCore, |
| 32 | + options: { |
| 33 | + /** |
| 34 | + * The number or range of digits to generate. |
| 35 | + * |
| 36 | + * @default { min: 1, max: 4 } |
| 37 | + */ |
| 38 | + length?: |
| 39 | + | number |
| 40 | + | { |
| 41 | + /** |
| 42 | + * The minimum number of digits to generate. |
| 43 | + */ |
| 44 | + min: number; |
| 45 | + /** |
| 46 | + * The maximum number of digits to generate. |
| 47 | + */ |
| 48 | + max: number; |
| 49 | + }; |
| 50 | + /** |
| 51 | + * Whether to pad the flight number up to 4 digits with leading zeros. |
| 52 | + * |
| 53 | + * @default false |
| 54 | + */ |
| 55 | + addLeadingZeros?: boolean; |
| 56 | + } = {} |
| 57 | +): string { |
| 58 | + const { length = { min: 1, max: 4 }, addLeadingZeros = false } = options; |
| 59 | + const flightNumber = numeric(fakerCore, { |
| 60 | + length, |
| 61 | + allowLeadingZeros: false, |
| 62 | + }); |
| 63 | + return addLeadingZeros ? flightNumber.padStart(4, '0') : flightNumber; |
| 64 | +} |
0 commit comments