I got rejected in tech screen yesterday. I was asked to write a JavaScript function and send it over email. The question was:
Could you please write a JavaScript function to compare two strings that look like phone numbers and indicate whether the digits in both strings match? Your code should compare only the digits of the input, ignore any letters or punctuation, and ignore the fact that country/area codes can be optional.
I wasn’t sure if regex would be an acceptable solution so I implemented it two ways; please, let me know what I could have done better.
"use strict"
var CompareNumbers = function () {
//#region private variables
var _phoneNumber1;
var _phoneNumber2;
var _minPhoneLength = 1;
var _validateResult;
var _notValidMessage = "Not a valid Phone Number";
var _successMessage = "Match";
var _failureMessage = "Not a Match";
var _inputArray1;
var _inputArray2;
var _numArray1;
var _numArray2;
//#endregion
//#region private functions
//function using regex to remove spaces & braces etc
var _compNumbersUsingRegex = function (input1, input2) {
if (_validateInputs(input1, input2)) {
_phoneNumber1 = input1.replace(/[^0-9]+/g, '');
_phoneNumber2 = input2.replace(/[^0-9]+/g, '');
if (_validateInputs(_phoneNumber1, _phoneNumber2)) {
if (_phoneNumber1 == _phoneNumber2) {
return _successMessage;
}
else {
return _failureMessage;
}
}
return _notValidMessage;
}
else {
return _notValidMessage;
}
}
//function using arrays for comparison
var _compNumbersUsingArray = function (input1, input2) {
if (_validateInputs(input1, input2)) {
_inputArray1 = new Array();
_inputArray2 = new Array();
_inputArray1 = input1.split('');
_numArray1 = new Array();
for (var i = 0; i < _inputArray1.length; i++) {
if (!isNaN(_inputArray1[i]) && _inputArray1[i] != ' ') {
_numArray1.push(_inputArray1[i]);
}
}
_inputArray2 = input2.split('');
_numArray2 = new Array();
for (var i = 0; i < _inputArray2.length; i++) {
if (!isNaN(_inputArray2[i]) && _inputArray2[i] != ' ') {
_numArray2.push(_inputArray2[i]);
}
}
if (_validateInputs()) {
return _numArray1.toString() == _numArray2.toString() ? _successMessage : _failureMessage;
}
else {
return _notValidMessage;
}
}
else {
return _notValidMessage;
}
}
//Helper funciton to validate if inputs exceed a minimum number declared in variable section
function _validateInputs(validate1, validate2) {
if (validate1.length < _minPhoneLength || validate2.length < _minPhoneLength) {
return false;
}
else {
return true;
}
}
//#endregion
//#region public members
var publics = {
comparePhoneNumbers1: _compNumbersUsingArray,
comparePhoneNumbers2: _compNumbersUsingRegex
};
return publics;
//#endregion
}();