JSFiddle - React, Tailwind, and code Playground

by kevinmicke

HTML

<p>Testing different left padding techniques to find the most versatile and quickest method for this Stack Overflow question: <a href="http://stackoverflow.com/questions/1267283/how-can-i-create-a-zerofilled-value-using-javascript">http://stackoverflow.com/questions/1267283/how-can-i-create-a-zerofilled-value-using-javascript</a></p>

Thanks to <a href="http://stackoverflow.com/users/1600814/jack-b">Jack B</a> on StackOverflow for putting together this test script, which is slightly modified here to compare his final version of the function: <a href="https://gist.github.com/NextToNothing/6325915">https://gist.github.com/NextToNothing/6325915</a>

<p>Open the console in your browser to see the results.</p>

JavaScript

var theNum = 9;
var thePadNum = 2000;
// Jack B
function pad1(str, max, padder) {
  padder = typeof pad1der === "undefined" ? "0" : padder;
  return str.toString().length < max ? pad1(padder.toString() + str, max, padder) : str;
}
// Peter Bailey
function pad2( number, width )
{
  width -= number.toString().length;
  if ( width > 0 )
  {
    return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
  }
  return number + ""; // always return a string
}
// Wilco
function pad3(number, length) {
    // Setup
    var result = number.toString();
    var pad1 = length - result.length;
    while(pad1 > 0) {
      result = '0' + result;
    	pad1--;
    }
    return result;
}
// Coderjoe
// -- FAILS --
function pad4(num, numZeros) {
	var n = Math.abs(num);
	var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
	var zeroString = Math.pow(10,zeros).toString().substr(1);
	if( num < 0 ) {
		zeroString = '-' + zeroString;
	}
	return zeroString+n;
}
// Jonathan Neal (1)
// -- FAILS --
function pad5(num, count) {
    return [Math.pow(10, count - num.toString().length), num].join('').substr(1);
};
// Jonathan Neal (2)
// -- FAILS --
function pad6(num, count) {
    var pad = (num + '').length - count;
    while(--pad > -1) {
        num = '0' + num;
    }
    return num;
};
// Rodringo
// -- FAILS --
function pad7(n, c) {
  if (isNaN(c))
    return null;
  return (new Array(c).join("0").substring(0, n.length-c)) + n; 
}
// Julian Mann
// -- FAILS --
function pad8(n,pad) {
    p = Math.pow(10,pad);
    a = Math.abs(n);
    g = (n<0);
    return (a < p) ?  ((g ? '-' : '') + (p+a).toString().substring(1)) : n;
}
// profitehlolz
function pad9(n, p, c) {
    var pad_char = typeof c !== 'undefined' ? c : '0';
    var pad = new Array(1 + p).join(pad_char);
    return (pad + n).slice(-pad.length);
}
// Madbreaks
function pad10(toPad, length){
	padChar = "0";
    return (String(toPad).length < length)
        ? new Array(length - String(toPad).length +...