DEV Community

loading...

Discussion on: Daily Challenge #9 - What's Your Number?

Collapse
alvaromontoro profile image
Alvaro Montoro

JavaScript

I assumed the US phone number format that is (XXX) XXX-XXXX

const formatNumber = numbers => {

  let phoneNumber = "";

  // prerequisites:
  //   - input must be an array
  //   - with 10 elements
  //   - each element will be a single digit number
  if (
    Array.isArray(numbers) &&
    numbers.length === 10 &&
    numbers.every(n => n > -1 && n < 10)
  ) {
    // break the phone number into parts and generate the formmated string
    const areaCode = numbers.slice(0,3).join('');
    const firstPart = numbers.slice(3,6).join('');
    const secondPart = numbers.slice(6).join('');
    phoneNumber = `(${areaCode}) ${firstPart}-${secondPart}`;
  }

  return phoneNumber;
}

Live demo on CodePen (with an alternative version in one line).

Collapse
sturzl profile image
Avery

Why the one line solution?

Collapse
alvaromontoro profile image
Alvaro Montoro

No real reason. Both do the same, the first one is more verbose and easier to understand. I deleted the one-line one to avoid any confusion.