Sharing of the four digital kilobytes of characters formatting methods implemented by JS, js kilobytes

Source: Internet
Author: User

Sharing of the four digital kilobytes of characters formatting methods implemented by JS, js kilobytes

The so-called number is represented by a comma (,) between each three digits starting from the single digit. For example, "10,000 ". In response to this requirement, I initially wrote a function like this:
Copy codeThe Code is as follows:
// Method 1
Function toThousands (num ){
Var result = [], counter = 0;
Num = (num | 0). toString (). split ('');
For (var I = num. length-1; I> = 0; I --){
Counter ++;
Result. unshift (num [I]);
If (! (Counter % 3) & I! = 0) {result. unshift (',');}
}
Return result. join ('');
}

Method 1 converts a number to a string, splits it into an array, and inserts the elements in the array one by one at the beginning of the new array (result. Every time one element is inserted, counter counts the number once (plus 1). When counter is a multiple of 3, a comma is inserted, but note the beginning (when I is 0) no comma. Finally, the result is obtained by calling the join method of the new array.

The method is clear and easy to understand. It also takes some time in the project. But intuition tells me that its performance is not good.

Method 2-method 1 string Edition
Copy codeThe Code is as follows:
// Method 2
Function toThousands (num ){
Var result = '', counter = 0;
Num = (num | 0). toString ();
For (var I = num. length-1; I> = 0; I --){
Counter ++;
Result = num. charAt (I) + result;
If (! (Counter % 3) & I! = 0) {result = ',' + result ;}
}
Return result;
}

Method 2 is an improved version of method 1, which never splits strings into arrays and always operates on strings.

Method 3 -- three digits at the end of loop matching
Copy codeThe Code is as follows:
// Method 3
Function toThousands (num ){
Var num = (num | 0). toString (), re =/\ d {3} $/, result = '';
While (re. test (num )){
Result = RegExp. lastMatch + result;
If (num! = RegExp. lastMatch ){
Result = ',' + result;
Num = RegExp. leftContext;
} Else {
Num = '';
Break;
}
}
If (num) {result = num + result ;}
Return result;
}

Method 3 is a completely different algorithm. The regular expression cyclically matches the three digits at the end of the string. Each time a match is performed, the comma and the matched content are inserted at the beginning of the result string, then assign the Matching target (num) to the unmatched content (RegExp. leftContext ). In addition, note the following:

1. If the number of digits is a multiple of 3, the last matched number must be three digits, but a comma is not required before the first three digits;
2. If the number of digits is not a multiple of 3, then the num variable will definitely have 1 to 2 digits. After the loop, insert the remaining digits to the beginning of the result string.

Although method 3 reduces the number of loops (three characters are processed in one loop), the use of regular expressions increases consumption to some extent.

Method 4 -- string version of method 3
Copy codeThe Code is as follows:
// Method 4
Function toThousands (num ){
Var num = (num | 0). toString (), result = '';
While (num. length> 3 ){
Result = ',' + num. slice (-3) + result;
Num = num. slice (0, num. length-3 );
}
If (num) {result = num + result ;}
Return result;
}

In fact, the function of intercepting the last three characters can be achieved through the slice, substr, or substring method of the string type. This avoids the use of regular expressions.

Method 5-grouping and merging
Copy codeThe Code is as follows:
// Method 5
Function toThousands (num ){
Var num = (num | 0). toString (), temp = num. length % 3;
Switch (temp ){
Case 1:
Num = '00' + num;
Break;
Case 2:
Num = '0' + num;
Break;
}
Return num. match (/\ d {3}/g). join (','). replace (/^ 0 + /,'');
}

First, add the number of digits to a multiple of 3, and use a regular expression to cut the number into a group of every three digits, and then add a comma through the join method, finally, remove the supplemented 0.

Method 6-Lazy Method
Copy codeThe Code is as follows:
// Method 6
Function toThousands (num ){
Return (num | 0). toString (). replace (/(\ d )(? = (? : \ D {3}) + $)/g, '$1 ,');
}

I always think that this formatting can be done by replacing it with a regular expression, but I need to use assertions and other writing methods, but I am not familiar with this part. After Google, I found such a regular expression, which is probably the shortest implementation of the Code.

Test Results

Number Execution of 5000 elapsed time (MS)
Method 1 Method 2 Method 3 Method 4 Method 5 Method 6
1 4 1 3 1 14 2
10 14 1 3 0 7 2
100 12 1 2 4 5 3
1000 13 2 3 2 9 5
10000 21 4 3 1 6 3
100000 21 3 2 1 5 6

The strong comparison between method 1 and method 2 shows that the efficiency of string operations is much higher than that of Array Operations. The test result of Method 6 shows that the code length has nothing to do with the performance. The overall performance of Method 4 is the best (but why is the performance decreased when num is 100?), the main reason is:

1. Comparison Method 1 and 2: Reduce the number of cycles by operating three characters instead of one character each time;
2. Compared with method 3, Method 5, and Method 6, regular expressions are not used to reduce consumption.

Finally, I chose Method 4 as the final optimization solution. If you have better implementation methods or suggestions for improvement, you can post comments.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.