JAVASCRIPT 23
Sprintf.js Guest on 4th May 2021 10:50:56 AM
  1. function sprintf() {
  2. /*
  3.  * Copyright (c) 2013 Kevin van Zonneveld (http://kvz.io)
  4.  * and Contributors (http://phpjs.org/authors)
  5.  *
  6.  * Permission is hereby granted, free of charge, to any person obtaining a copy of
  7.  * this software and associated documentation files (the "Software"), to deal in
  8.  * the Software without restriction, including without limitation the rights to
  9.  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  10.  * of the Software, and to permit persons to whom the Software is furnished to do
  11.  * so, subject to the following conditions:
  12.  *
  13.  * The above copyright notice and this permission notice shall be included in all
  14.  * copies or substantial portions of the Software.
  15.  *
  16.  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17.  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18.  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19.  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20.  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21.  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22.  * SOFTWARE.
  23. */
  24.   //  discuss at: http://phpjs.org/functions/sprintf/
  25.   // original by: Ash Searle (http://hexmen.com/blog/)
  26.   // improved by: Michael White (http://getsprink.com)
  27.   // improved by: Jack
  28.   // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  29.   // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  30.   // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  31.   // improved by: Dj
  32.   // improved by: Allidylls
  33.   //    input by: Paulo Freitas
  34.   //    input by: Brett Zamir (http://brett-zamir.me)
  35.   //   example 1: sprintf("%01.2f", 123.1);
  36.   //   returns 1: 123.10
  37.   //   example 2: sprintf("[%10s]", 'monkey');
  38.   //   returns 2: '[    monkey]'
  39.   //   example 3: sprintf("[%'#10s]", 'monkey');
  40.   //   returns 3: '[####monkey]'
  41.   //   example 4: sprintf("%d", 123456789012345);
  42.   //   returns 4: '123456789012345'
  43.   //   example 5: sprintf('%-03s', 'E');
  44.   //   returns 5: 'E00'
  45.  
  46.   var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g;
  47.   var a = arguments;
  48.   var i = 0;
  49.   var format = a[i++];
  50.  
  51.   // pad()
  52.   var pad = function (str, len, chr, leftJustify) {
  53.     if (!chr) {
  54.       chr = ' ';
  55.     }
  56.     var padding = (str.length >= len) ? '' : new Array(1 + len - str.length >>> 0)
  57.       .join(chr);
  58.     return leftJustify ? str + padding : padding + str;
  59.   };
  60.  
  61.   // justify()
  62.   var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
  63.     var diff = minWidth - value.length;
  64.     if (diff > 0) {
  65.       if (leftJustify || !zeroPad) {
  66.         value = pad(value, minWidth, customPadChar, leftJustify);
  67.       } else {
  68.         value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
  69.       }
  70.     }
  71.     return value;
  72.   };
  73.  
  74.   // formatBaseX()
  75.   var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
  76.     // Note: casts negative numbers to positive ones
  77.     var number = value >>> 0;
  78.     prefix = prefix && number && {
  79.       '2': '0b',
  80.       '8': '0',
  81.       '16': '0x'
  82.     }[base] || '';
  83.     value = prefix + pad(number.toString(base), precision || 0, '0', false);
  84.     return justify(value, prefix, leftJustify, minWidth, zeroPad);
  85.   };
  86.  
  87.   // formatString()
  88.   var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
  89.     if (precision != null) {
  90.       value = value.slice(0, precision);
  91.     }
  92.     return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
  93.   };
  94.  
  95.   // doFormat()
  96.   var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
  97.     var number, prefix, method, textTransform, value;
  98.  
  99.     if (substring === '%%') {
  100.       return '%';
  101.     }
  102.  
  103.     // parse flags
  104.     var leftJustify = false;
  105.     var positivePrefix = '';
  106.     var zeroPad = false;
  107.     var prefixBaseX = false;
  108.     var customPadChar = ' ';
  109.     var flagsl = flags.length;
  110.     for (var j = 0; flags && j < flagsl; j++) {
  111.       switch (flags.charAt(j)) {
  112.       case ' ':
  113.         positivePrefix = ' ';
  114.         break;
  115.       case '+':
  116.         positivePrefix = '+';
  117.         break;
  118.       case '-':
  119.         leftJustify = true;
  120.         break;
  121.       case "'":
  122.         customPadChar = flags.charAt(j + 1);
  123.         break;
  124.       case '0':
  125.         zeroPad = true;
  126.         customPadChar = '0';
  127.         break;
  128.       case '#':
  129.         prefixBaseX = true;
  130.         break;
  131.       }
  132.     }
  133.  
  134.     // parameters may be null, undefined, empty-string or real valued
  135.     // we want to ignore null, undefined and empty-string values
  136.     if (!minWidth) {
  137.       minWidth = 0;
  138.     } else if (minWidth === '*') {
  139.       minWidth = +a[i++];
  140.     } else if (minWidth.charAt(0) == '*') {
  141.       minWidth = +a[minWidth.slice(1, -1)];
  142.     } else {
  143.       minWidth = +minWidth;
  144.     }
  145.  
  146.     // Note: undocumented perl feature:
  147.     if (minWidth < 0) {
  148.       minWidth = -minWidth;
  149.       leftJustify = true;
  150.     }
  151.  
  152.     if (!isFinite(minWidth)) {
  153.       throw new Error('sprintf: (minimum-)width must be finite');
  154.     }
  155.  
  156.     if (!precision) {
  157.       precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type === 'd') ? 0 : undefined;
  158.     } else if (precision === '*') {
  159.       precision = +a[i++];
  160.     } else if (precision.charAt(0) == '*') {
  161.       precision = +a[precision.slice(1, -1)];
  162.     } else {
  163.       precision = +precision;
  164.     }
  165.  
  166.     // grab value using valueIndex if required?
  167.     value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
  168.  
  169.     switch (type) {
  170.     case 's':
  171.       return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
  172.     case 'c':
  173.       return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
  174.     case 'b':
  175.       return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  176.     case 'o':
  177.       return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  178.     case 'x':
  179.       return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  180.     case 'X':
  181.       return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad)
  182.         .toUpperCase();
  183.     case 'u':
  184.       return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  185.     case 'i':
  186.     case 'd':
  187.       number = +value || 0;
  188.       // Plain Math.round doesn't just truncate
  189.       number = Math.round(number - number % 1);
  190.       prefix = number < 0 ? '-' : positivePrefix;
  191.       value = prefix + pad(String(Math.abs(number)), precision, '0', false);
  192.       return justify(value, prefix, leftJustify, minWidth, zeroPad);
  193.     case 'e':
  194.     case 'E':
  195.     case 'f': // Should handle locales (as per setlocale)
  196.     case 'F':
  197.     case 'g':
  198.     case 'G':
  199.       number = +value;
  200.       prefix = number < 0 ? '-' : positivePrefix;
  201.       method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
  202.       textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
  203.       value = prefix + Math.abs(number)[method](precision);
  204.       return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
  205.     default:
  206.       return substring;
  207.     }
  208.   };
  209.  
  210.   return format.replace(regex, doFormat);
  211. }

Paste-bin is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.