Skip to content

Commit

Permalink
add guard to loop to avoid stuck
Browse files Browse the repository at this point in the history
  • Loading branch information
kobenguyent authored Jan 9, 2025
1 parent 8fc3407 commit 6e9b69a
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion packages/falso/src/lib/phone-number.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,8 +269,11 @@ export function randPhoneNumber<Options extends PhoneNumberOptions = never>(

const generateValidPhoneNumber = (): string => {
let validNumber: string | null = null;
const maxRetries = 100; // Set a limit to prevent infinite loops
let attempts = 0;

while (!validNumber) {
while (!validNumber && attempts < maxRetries) {
attempts++;
const phoneNumber = randMask({
mask: randElement(formats),
});
Expand All @@ -281,6 +284,12 @@ export function randPhoneNumber<Options extends PhoneNumberOptions = never>(
}
}

if (!validNumber) {
throw new Error(
`Failed to generate a valid phone number after ${maxRetries} attempts.`
);
}

return validNumber;
};

Expand All @@ -290,3 +299,4 @@ export function randPhoneNumber<Options extends PhoneNumberOptions = never>(

return fake(phoneNumber, options);
}

0 comments on commit 6e9b69a

Please sign in to comment.