fsdb/organizers/by_phone.ts

42 lines
1.1 KiB
TypeScript

/**
* FSDB Organizer: By Phone
*
* Organizes by splitting a phone number into its components:
*
* Eg: 1-213-555-1234 => 1/213/555/213-555-1234.json
*
* @module
*/
import sanitize from '../utils/sanitize.ts';
const PHONE_REGEX =
/^(?<country_code>\+?\d{1,3})?[\s.x-]?\(?(?<area_code>\d{3})\)?[\s.x-]?(?<central_office_code>\d{3})[\s.x-]?(?<subscriber_code>\d{4})$/;
export default function by_phone(phone: string): string[] {
const { groups: { country_code, area_code, central_office_code, subscriber_code } } = {
groups: {
country_code: undefined,
area_code: undefined,
central_office_code: undefined,
subscriber_code: undefined
},
...(phone.match(PHONE_REGEX) ?? {})
};
if (
typeof area_code !== 'string' || typeof central_office_code !== 'string' ||
typeof subscriber_code !== 'string'
) {
return [];
}
const normalized_number = `${sanitize(area_code)}-${sanitize(central_office_code)}-${sanitize(subscriber_code)}`;
return [
sanitize(country_code ?? '1'),
sanitize(area_code),
sanitize(central_office_code),
normalized_number,
`${normalized_number}.json`
];
}