我如何在 TypeScript 中构建区域感知电话号码生成器
发布: (2025年12月11日 GMT+8 15:36)
2 min read
原文: Dev.to
Source: Dev.to
挑战
不同的格式:美国号码的形式是 (###) ###-####,而其他国家可能是 #### ####。
唯一性:在为数据库种子生成 10,000 条号码时,不能出现重复。
效率:需要快速生成这些号码。
解决方案:模式替换
与其为每个国家硬编码规则,我采用了 模式匹配 的方式。每个国家都有类似下面的配置方案:
const plan = {
countryCode: "+1",
nationalPattern: "(###) ###-####", // # 代表一个数字
digits: 10
};
核心循环(TypeScript)
下面是简化版的 generatePhoneNumbers 函数。它使用 Set 来跟踪唯一性,并动态填充模式:
export function generatePhoneNumbers(options: any) {
const { quantity, ensureUnique } = options;
const results = [];
const seen = new Set(); // O(1) lookup for uniqueness
let attempts = 0;
const maxAttempts = quantity * 10; // Prevent infinite loops
while (results.length < quantity && attempts < maxAttempts) {
attempts++;
// 1. Generate raw random digits
const digits = createRandomDigits(10);
// 2. Uniqueness Check
if (ensureUnique && seen.has(digits)) {
continue; // Skip duplicate
}
seen.add(digits);
// 3. Format using Pattern Matching (The magic part)
// We iterate through the pattern and replace '#' with our digits
results.push({
formatted: insertDigits("(###) ###-####", digits),
raw: digits
});
}
return results;
}
insertDigits 辅助函数会遍历字符串:遇到 # 时从随机数字串中取出一个数字;否则保留原字符(如括号或空格)。
试一试
我把这套逻辑(以及对 50 多个国家的支持和 CSV 导出功能)封装成了一个免费在线工具。
它完全在浏览器中运行,隐私友好且速度极快。
祝编码愉快!