Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(location)!: throw error if state is unknown #1760

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions src/modules/location/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Faker } from '../..';
import { FakerError } from '../..';
import { deprecated } from '../../internal/deprecated';

/**
Expand Down Expand Up @@ -48,25 +49,31 @@ export class LocationModule {
/**
* Generates random zip code from state abbreviation. If state abbreviation is
* not specified, a random zip code is generated according to the locale's zip format.
* Only works for locales with postcode_by_state definition. If a locale does not
* have a postcode_by_state definition, a random zip code is generated according
* to the locale's zip format.
* Only works for locales with postcode_by_state definition.
*
* @param state The abbreviation of the state to generate the zip code for.
*
* @throws If a locale does not have a postcode_by_state definition.
*
* @example
* fakerUS.location.zipCodeByState("AK") // '99595'
* fakerUS.location.zipCodeByState("??") // '47683-9880'
*
* @since 8.0.0
*/
zipCodeByState(state: string): string {
const zipRange = this.faker.definitions.location.postcode_by_state?.[state];
if (zipRange) {
return String(this.faker.number.int(zipRange));
} else {
const stateList = Object.keys(
this.faker.definitions.location.postcode_by_state ?? {}
);
throw new FakerError(
`faker.definitions.location.postcode_by_state only contains data for [${stateList.join(
', '
)}]`
);
}

return this.zipCode();
}

/**
Expand Down