Saturday, September 30, 2023
HomeSoftware EngineeringLearn how to Resolve the Grouped by Commas Problem in Javascript

Learn how to Resolve the Grouped by Commas Problem in Javascript


The problem

End the answer in order that it takes an enter n (integer) and returns a string that’s the decimal illustration of the quantity grouped by commas after each 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 answer in Javascript

Choice 1:

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

Choice 2:

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

Choice 3:

operate groupByCommas(n) {
  var s = n.toString(),
      r = [];
  s = reverse(s);
  for (var i = 0, l = s.size; i < l; i += 3) {
    r.push(s.substr(i, 3));
  }
  return reverse(r.be part of(','));
}
operate reverse(s) {
  return s.break up('').reverse().be part of('');
}

Take a look at instances to validate our resolution

describe("Exams", () => {
  it("check", () => {
    Take a look at.assertEquals(groupByCommas(1), '1');
    Take a look at.assertEquals(groupByCommas(10), '10');
    Take a look at.assertEquals(groupByCommas(100), '100');
    Take a look at.assertEquals(groupByCommas(1000), '1,000');
    Take a look at.assertEquals(groupByCommas(10000), '10,000');
    Take a look at.assertEquals(groupByCommas(100000), '100,000');
    Take a look at.assertEquals(groupByCommas(1000000), '1,000,000');
    Take a look at.assertEquals(groupByCommas(35235235), '35,235,235');
  });
});
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments