How to Solve the Grouped by Commas Challenge in Javascript


The challenge

Finish the solution so that it takes an input n (integer) and returns a string that is the decimal representation of the number grouped by commas after every 3 digits.

Assume: 0 <= n < 2147483647

Examples:

       1  ->           "1"
      10  ->          "10"
     100  ->         "100"
    1000  ->       "1,000"
   10000  ->      "10,000"
  100000  ->     "100,000"
 1000000  ->   "1,000,000"
35235235  ->  "35,235,235"

The solution in Javascript

Option 1:

function groupByCommas(n) {
  return n.toLocaleString()
}

Option 2:

function groupByCommas(n) {
  return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

Option 3:

function groupByCommas(n) {
  var s = n.toString(),
      r = [];
  s = reverse(s);
  for (var i = 0, l = s.length; i < l; i += 3) {
    r.push(s.substr(i, 3));
  }
  return reverse(r.join(','));
}
function reverse(s) {
  return s.split('').reverse().join('');
}

Test cases to validate our solution

describe("Tests", () => {
  it("test", () => {
    Test.assertEquals(groupByCommas(1), '1');
    Test.assertEquals(groupByCommas(10), '10');
    Test.assertEquals(groupByCommas(100), '100');
    Test.assertEquals(groupByCommas(1000), '1,000');
    Test.assertEquals(groupByCommas(10000), '10,000');
    Test.assertEquals(groupByCommas(100000), '100,000');
    Test.assertEquals(groupByCommas(1000000), '1,000,000');
    Test.assertEquals(groupByCommas(35235235), '35,235,235');
  });
});