Questions example phoneNumber

Viewed 88

I am a student studying JavaScript. It hasn't been long since I studied. Example, createPhoneNumber The length is up to 11 digits. I wrote the code in question like this.

function createPhoneNumber(arr) {
    let first = '(010)';
      if(arr.length === 11){
       return `(${arr.slice(0,3).join('')})${arr.slice(3,7).join('')}-${arr.slice(7,11).join('')}`;
     }
     return `${first}${arr.slice(0,4).join('')}-${arr.slice(4,8).join('')}`;
     }

I think it's very messy code.

Is it better to add a new variable to make it shorter and simpler?

3 Answers

This can be done by Regex:

function createPhoneNumber(arr) {
   let first = '(010)';
   // the submatch (\D)? is intended to get an empty match when the length of arr is not 11
   let reg = arr.length == 11 ? /(\d{3})(\d{4})(\d{4})/ : /(\D)?(\d{4})(\d{0,4})(\d{0,})/;
   return arr.join('').replace(reg, (match, $1, $2, $3) => ($1 ? "(" + $1 + ")" : first) + $2 + "-" + $3);
}

console.log(createPhoneNumber([0,1,0,1,2,3,4,5,6,7,8]));
console.log(createPhoneNumber([1,2,3,4,5,6]));
console.log(createPhoneNumber([1,2,3,4,5,6,7,8,9,0,0,0,0,0]));

You want it shorter and simpler? This is subjective but I believe the following applies. Also, I wasn't sure if you misused your 11th digit in your function so... I made it work with 10.

function createPhoneNumber(arr) {
  const arrL = arr.length;
  let arrI = arrL - 4;
  arr.splice(arrI, 0, "-");
  arr.splice(arrI -= 3, 0, ")");
  arr.splice(0, 0, arrL === 10 ? "(" : "(010");
  return arr.join("");
}

If it's just a matter of readability, I suggest a few changes:

  1. Export hard coded values to const.
  2. Don't duplicate your code! like the complicated return you had.
  3. It did look messy - do I decided to separate the number to 3 parts - 3 variables, and use 1 return

const PRE_FIRST = '(010)';
const FULL_NUMBER_LENGTH = 11;

function createPhoneNumber(arr) {
  let isFullPhone = FULL_NUMBER_LENGTH === arr.length;
  let first = isFullPhone ? arr.slice(0, 3).join('') : PRE_FIRST;
  let second = (isFullPhone ? arr.slice(3, 7) : arr.slice(0, 4)).join('');
  let third = (isFullPhone ? arr.slice(7, 11) : arr.slice(4, 8)).join('');
  return `${first}-${second}-${third}`;
}

Related