phone-number-generator-js
Version:
Generates a random phone number following the E.164 international standard
61 lines (60 loc) • 2.94 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.isPhoneNumberValid = void 0;
var libphonenumber_js_1 = require("libphonenumber-js");
var class_validator_1 = require("class-validator");
var lodash_1 = require("lodash");
var countryPhoneData_1 = require("./countryPhoneData");
function generatePhoneNumber(config) {
for (var i = 0; i < 100; i++) {
var countryPhoneData = getCountryPhoneDataByConfig(config);
for (var j = 0; j < 1000; j++) {
var phoneNumber = getRandomPhoneNumber(countryPhoneData, config === null || config === void 0 ? void 0 : config.withoutCountryCode);
if (isPhoneNumberValid(phoneNumber, countryPhoneData, config === null || config === void 0 ? void 0 : config.withoutCountryCode)) {
return phoneNumber;
}
}
if (config) {
break;
}
}
throw new Error("Failed to generate phone number");
}
exports.default = generatePhoneNumber;
function isPhoneNumberValid(phoneNumber, countryPhoneData, withoutCountryCode) {
if (withoutCountryCode) {
return countryPhoneData !== undefined && (0, libphonenumber_js_1.isValidNumberForRegion)(phoneNumber, countryPhoneData.alpha2);
}
return (0, libphonenumber_js_1.isValidPhoneNumber)(phoneNumber) && (0, class_validator_1.isPhoneNumber)(phoneNumber);
}
exports.isPhoneNumberValid = isPhoneNumberValid;
function getRandomPhoneNumber(countryPhoneData, withoutCountryCode) {
var _a;
if (withoutCountryCode === void 0) { withoutCountryCode = false; }
var randomMobileBeginWith = (_a = (0, lodash_1.sample)(countryPhoneData.mobile_begin_with)) !== null && _a !== void 0 ? _a : "";
var randomPhoneNumberSuffix = getRandomPhoneNumberSuffix(countryPhoneData.phone_number_lengths[0] - randomMobileBeginWith.length);
return "" + (withoutCountryCode ? '' : '+' + countryPhoneData.country_code) + randomMobileBeginWith + randomPhoneNumberSuffix;
}
function getRandomPhoneNumberSuffix(phoneNumberLength) {
return "" + (0, lodash_1.random)(2, 10) + getRandomNumberInLength(phoneNumberLength - 1);
}
function getRandomNumberInLength(length) {
var min = Math.pow(10, length - 1);
var max = Math.pow(10, length) - 1;
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getCountryPhoneDataByConfig(config) {
var _a;
if (config === void 0) { config = {}; }
var countryPhoneData;
if (!config || !config.countryName) {
countryPhoneData = (0, lodash_1.sample)(countryPhoneData_1.countryPhoneDataArray);
}
else {
countryPhoneData =
(_a = countryPhoneData_1.countryPhoneDataArray.find(function (countryPhoneData) { return countryPhoneData.country_name === config.countryName; })) !== null && _a !== void 0 ? _a : (function () {
throw new Error("Invalid country name");
})();
}
return countryPhoneData;
}
;