/javascript/phone-number/phone-number.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
var phoneNumber = function(number) {

  var INVALID_NUMBER = "0000000000";

  // Return a cleaned version of the number
  var cleanNumber = function(number) {
    number = number.replace(/\D/g, '');
    if (number.length != 10) {
      if (number.length == 11 && number[0] == '1') {
        // Use the last 10 digits of 11 digit number if it begins with 1
        number = number.slice(1);
      } else {
        number = INVALID_NUMBER;
      }
    }

    return number;
  };

  // Precalculate these since the number doesn't change.
  this.clean_number = cleanNumber(number);
};


phoneNumber.prototype = {

  // Return the cleaned up digit string
  number: function() {
    return this.clean_number;
  },

  // Return the area code
  areaCode: function() {
    return this.clean_number.slice(0,3);
  },

  // Return the formatted phone number
  toString: function() {
    return ('(' + this.areaCode() + ') ' +
      this.clean_number.slice(3,6) + '-' + this.clean_number.slice(6));
  }
};

module.exports = phoneNumber;

Comments

Don't pre-calculate area code or formatted string. Still cleaning number on initialization as this is more of an input sanitization.

helenst commented 6 April 2015 at 09:04 UTC

You're not logged in right now. Please login via GitHub to comment