-2

I have built a function that formats a number using commas, similar to what the toLocaleString method does. To achieve that, I used a regular expression and recursion. However, I have a feeling that this could've been done better.

I did some research but was not able to find the answer I'm looking for. So, my question is...Is there a better way to do this?

function transform(value) {
    const pureNumber = parseInt(value);
    const numberParts = [];
    function format(val) {
      let formatted = val.toString().split(/(\d{3})$/).filter(i => !!i).join(",");
      const splitted = formatted.split(",");
      if(splitted.length > 1){
        numberParts.unshift(splitted[1]);
        return format(splitted[0]);
      }
      numberParts.unshift(splitted[0]);
      return numberParts.join(",");
    }   
    return format(pureNumber.toString());    
}

const data = "1234567890";
const result = transform(data);
console.log(result);

What I need you to note is that I used a regular expression to split the string, however, I was wondering if there is a way to only use regular expressions to avoid the recursion? I.e., Is there a way to use the regular expression starting at the end of the string and repeating towards left?

Morfinismo
  • 4,985
  • 4
  • 19
  • 36
  • Why not use `toLocaleString`? – ryanve Dec 01 '20 at 23:08
  • @ryanve I am trying to expand my knowledge by attempting to do simple things. Maybe this question is not for this site. I am trying to learn from more experienced developers and thought this site would be ideal for this situation. – Morfinismo Dec 01 '20 at 23:11
  • How do we evaluate "better" ? What criteria determine what is good, not good and what is better? Also, I think this question might be better suited for [Code Review](https://codereview.stackexchange.com/) because there isn't a problem to be solved. – devlin carnate Dec 01 '20 at 23:13
  • @devlincarnate Thank you very much for your guidance. Next time I will consider this type of questions for Code Review. For now, I am thankful to the kind person who actually took interest in my concern and provided a real and solid answer. – Morfinismo Dec 01 '20 at 23:17

1 Answers1

-1

This can be accomplished much simpler using a single Regex expression:

function transform(value) {
  return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

// Works with string
console.log(transform("0123456789"));

// And numbers
console.log(transform(1234567890));

This regex will look in the string for any point that has 3 digits in a row after it and will make sure that point only has exactly multiples of 3 digits.


This was discovered in the first part of a post: How to print a number with commas as thousands separators in JavaScript

BudBurriss
  • 136
  • 5