DEV Community

Riches
Riches

Posted on

Algorithm To Create Phone Number "Codewars"

Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.
Don't forget the space after the closing parentheses!
E.g:
Given ([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
It should return "(123) 456-7890"

Algorithm.

Step-1 - Use an if statement to ensure that the length of the array is 10 digits.

Step-2 - Using the slice() method in javascript we need to divide the array into three parts based on the format given to us. the first part will hold the first 3 digits, the second part will hold the next three numbers and the last part will hold the last four digits.

step-3 - concatenate the three parts together into a new variable. Don't forget to add the parentheses, the space after the closing parentheses and the dash.

Step-4 - return your variable

function createPhoneNumber(numbers) {
    // Check if the numbers array has exactly 10 digits.
    if (numbers.length !== 10) {
        return "Invalid input.";
    }
    // Using slice() method to get the first 3 second 3 and last 4
    let firstPart = numbers.slice(0, 3).join('');
    let secondPart = numbers.slice(3, 6).join('');
    let thirdPart = numbers.slice(6).join('');

    const phoneNumber = `(${firstPart}) ${secondPart}-${thirdPart}`;

    return phoneNumber;
}
console.log(createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)