sprintf.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. function sprintf( ) {
  2. // Return a formatted string
  3. //
  4. // version: 903.3016
  5. // discuss at: http://phpjs.org/functions/sprintf
  6. // + original by: Ash Searle (http://hexmen.com/blog/)
  7. // + namespaced by: Michael White (http://getsprink.com)
  8. // + tweaked by: Jack
  9. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  10. // + input by: Paulo Ricardo F. Santos
  11. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  12. // + input by: Brett Zamir (http://brettz9.blogspot.com)
  13. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  14. // * example 1: sprintf("%01.2f", 123.1);
  15. // * returns 1: 123.10
  16. // * example 2: sprintf("[%10s]", 'monkey');
  17. // * returns 2: '[ monkey]'
  18. // * example 3: sprintf("[%'#10s]", 'monkey');
  19. // * returns 3: '[####monkey]'
  20. var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
  21. var a = arguments, i = 0, format = a[i++];
  22. // pad()
  23. var pad = function(str, len, chr, leftJustify) {
  24. if (!chr) chr = ' ';
  25. var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
  26. return leftJustify ? str + padding : padding + str;
  27. };
  28. // justify()
  29. var justify = function(value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
  30. var diff = minWidth - value.length;
  31. if (diff > 0) {
  32. if (leftJustify || !zeroPad) {
  33. value = pad(value, minWidth, customPadChar, leftJustify);
  34. } else {
  35. value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
  36. }
  37. }
  38. return value;
  39. };
  40. // formatBaseX()
  41. var formatBaseX = function(value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
  42. // Note: casts negative numbers to positive ones
  43. var number = value >>> 0;
  44. prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
  45. value = prefix + pad(number.toString(base), precision || 0, '0', false);
  46. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  47. };
  48. // formatString()
  49. var formatString = function(value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
  50. if (precision != null) {
  51. value = value.slice(0, precision);
  52. }
  53. return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
  54. };
  55. // doFormat()
  56. var doFormat = function(substring, valueIndex, flags, minWidth, _, precision, type) {
  57. var number;
  58. var prefix;
  59. var method;
  60. var textTransform;
  61. var value;
  62. if (substring == '%%') return '%';
  63. // parse flags
  64. var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false, customPadChar = ' ';
  65. var flagsl = flags.length;
  66. for (var j = 0; flags && j < flagsl; j++) switch (flags.charAt(j)) {
  67. case ' ': positivePrefix = ' '; break;
  68. case '+': positivePrefix = '+'; break;
  69. case '-': leftJustify = true; break;
  70. case "'": customPadChar = flags.charAt(j+1); break;
  71. case '0': zeroPad = true; break;
  72. case '#': prefixBaseX = true; break;
  73. }
  74. // parameters may be null, undefined, empty-string or real valued
  75. // we want to ignore null, undefined and empty-string values
  76. if (!minWidth) {
  77. minWidth = 0;
  78. } else if (minWidth == '*') {
  79. minWidth = +a[i++];
  80. } else if (minWidth.charAt(0) == '*') {
  81. minWidth = +a[minWidth.slice(1, -1)];
  82. } else {
  83. minWidth = +minWidth;
  84. }
  85. // Note: undocumented perl feature:
  86. if (minWidth < 0) {
  87. minWidth = -minWidth;
  88. leftJustify = true;
  89. }
  90. if (!isFinite(minWidth)) {
  91. throw new Error('sprintf: (minimum-)width must be finite');
  92. }
  93. if (!precision) {
  94. precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : void(0);
  95. } else if (precision == '*') {
  96. precision = +a[i++];
  97. } else if (precision.charAt(0) == '*') {
  98. precision = +a[precision.slice(1, -1)];
  99. } else {
  100. precision = +precision;
  101. }
  102. // grab value using valueIndex if required?
  103. value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
  104. switch (type) {
  105. case 's': return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
  106. case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
  107. case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  108. case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  109. case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  110. case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
  111. case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  112. case 'i':
  113. case 'd': {
  114. number = parseInt(+value);
  115. prefix = number < 0 ? '-' : positivePrefix;
  116. value = prefix + pad(String(Math.abs(number)), precision, '0', false);
  117. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  118. }
  119. case 'e':
  120. case 'E':
  121. case 'f':
  122. case 'F':
  123. case 'g':
  124. case 'G': {
  125. number = +value;
  126. prefix = number < 0 ? '-' : positivePrefix;
  127. method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
  128. textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
  129. value = prefix + Math.abs(number)[method](precision);
  130. return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
  131. }
  132. default: return substring;
  133. }
  134. };
  135. return format.replace(regex, doFormat);
  136. }