Add 0 to the number string in JS

Source: Internet
Author: User

A common problem is the date format of "1976-02-03 hh: mm: SS". My simple solution is as follows:

function formatDate(d) {  var D=['00','01','02','03','04','05','06','07','08','09']  with (d || new Date) return [    [getFullYear(), D[getMonth()+1]||getMonth()+1, D[getDate()]||getDate()].join('-'),    [D[getHours()]||getHours(), D[getMinutes()]||getMinutes(), D[getSeconds()]||getSeconds()].join(':')  ].join(' ');}

This method is logically simple, and the rules are also simple. Besides the use of with (d | new date), it is not a skill. However, if you use this method to add 0 to the numeric string, the result is obviously not good. The moon shadow of 51js provides another solution:

function pad(num, n) {  return Array(n>num?(n-(''+num).length+1):0).join(0)+num;}

Call example:

Pad (100, 4); // output: 0100

Here, yueying analyzes the skills and balances the code length and efficiency:

Http://hi.baidu.com/akira_cn/blog/item/90ba2a8b07c867dafc1f1045.html

 

The last month's shadow recommends the "simple long storage method ":

/* Simple persistent storage method by lifesinger */function pad (Num, n) {var Len = num. tostring (). length; while (LEN <n) {num = "0" + num; Len ++;} return num ;}

This analysis is made in the blog of "shooting birds if you're okay:

Http://lifesinger.org/blog/2009/08/the-harm-of-tricky-code/

 

One thing that yueying did not do was to say, "Why is that short code less efficient ?".

The answer is "on the surface, replacing loops with array. Join is efficient, but the overhead of creating an array is forgotten ". Is there any way to do this? I have another idea. As follows:

/* Look-up table method (imperfect) by aimingoo */PAD = function (TBL) {return function (Num, n) {return (TBL [n = n-num.toString (). length]) | (TBL [N] = array (n ). join (0) + num) ;}} ([]);

This path is the same as the preceding formatdate (), but the table in formatdate () is not a definite array, and the array here is dynamically generated, then it is cached in TBL. The cached TBL [] array uses the form of a function call parameter, which is kept in the upper closure of the final pad () function. To make the above process clearer, I rearrange the code format as follows:

pad = function(tbl) {  return function(num, n) {    return (      ((tbl[n = n-num.toString().length]) ||       (tbl[n] = Array(n).join(0))) +      num    );  }}([]);

Okay. Here, don't worry. There are two other problems to solve. First, when 0 is not required, the above TBL [0] returns a null value, so it enters the second branch of the "|" operation, resulting in array () re-calculate once, that is to say, "The efficiency is actually the lowest if you do not add 0 ". Second, when the num length is greater than N, it is changed to "Adding negative numbers to zero ". "Adding a negative number to zero" is obviously not acceptable. Generally, this is treated as "No need to fill zero", and then the first problem is returned.

 

These two problems can be solved at one time. In fact, they are judged at one more time:

/* Look-up table method (improved version) by aimingoo */PAD = function (TBL) {return function (Num, n) {return (0> = (n = n-num.toString (). length ))? Num: (TBL [N] | (TBL [N] = array (n + 1). Join (0) + num ;}} ([]);

Of course, you can also sort out the code format as before. Or use a version that does not require "(functional language) continuous operation or other techniques:

/* Look-up table method (procedural version) by aimingoo */PAD = function () {var TBL = []; return function (Num, n) {var Len = n-num.toString (). length; If (LEN <= 0) return num; If (! TBL [Len]) TBL [Len] = (new array (LEN + 1). Join ('0'); Return TBL [Len] + num ;}}();

This is always the case for algorithms. If it is not time for space, or space for time. The "simple long storage method" of shoot sculpture is the method of time-to-space change, and The lookup rule here is the solution of Time-to-space change. This function will persist a string array in TBL. If num changes frequently, the efficiency will not be greatly improved-for systems with too many changes, caching will be meaningless. In fact, the logic is almost the same, just a little less than a step.

 

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.