Number.prototype.fillZero
0で詰めるJavaScriptのベンチマーク - FFFF - 0x
Number.prototype.fillZero = function(n){ return (0 .toFixed(n) + this).slice(-n); }
ゴルフ的には「 (''+ 1e20 + this).slice(-n) 」としたいとこだが,20桁までになるのでこれで妥協。
js> dis(function(n) ('_' + Math.pow(10, n) + this).slice(-n) ) flags: LAMBDA EXPR_CLOSURE INTERPRETED main: 00000: string "_" 00003: name "Math" 00006: callprop "pow" 00009: int8 10 00011: getarg 0 00014: call 2 00017: add 00018: this 00019: add 00020: group 00021: callprop "slice" 00024: getarg 0 00027: neg 00028: call 1 00031: return 00032: stop Source notes: 0: 6 [ 6] pcbase offset 3 2: 14 [ 8] xdelta 3: 14 [ 0] pcbase offset 11 5: 21 [ 7] pcbase offset 21 7: 28 [ 7] pcbase offset 28
js> dis(function(n) (0 .toFixed(n) + this).slice(-n) ) flags: LAMBDA EXPR_CLOSURE INTERPRETED main: 00000: zero 00001: callprop "toFixed" 00004: getarg 0 00007: call 1 00010: this 00011: add 00012: group 00013: callprop "slice" 00016: getarg 0 00019: neg 00020: call 1 00023: return 00024: stop Source notes: 0: 1 [ 1] pcbase offset 1 2: 7 [ 6] pcbase offset 7 4: 13 [ 6] pcbase offset 13 6: 20 [ 7] pcbase offset 20
たぶん速度も悪くない。