sprintf.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. // sprintf() for JavaScript 0.7-beta1
  2. // http://www.diveintojavascript.com/projects/javascript-sprintf
  3. //
  4. // Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com>
  5. // All rights reserved.
  6. var strRepeat = require('./helper/strRepeat');
  7. var toString = Object.prototype.toString;
  8. var sprintf = (function() {
  9. function get_type(variable) {
  10. return toString.call(variable).slice(8, -1).toLowerCase();
  11. }
  12. var str_repeat = strRepeat;
  13. var str_format = function() {
  14. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  15. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  16. }
  17. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  18. };
  19. str_format.format = function(parse_tree, argv) {
  20. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  21. for (i = 0; i < tree_length; i++) {
  22. node_type = get_type(parse_tree[i]);
  23. if (node_type === 'string') {
  24. output.push(parse_tree[i]);
  25. }
  26. else if (node_type === 'array') {
  27. match = parse_tree[i]; // convenience purposes only
  28. if (match[2]) { // keyword argument
  29. arg = argv[cursor];
  30. for (k = 0; k < match[2].length; k++) {
  31. if (!arg.hasOwnProperty(match[2][k])) {
  32. throw new Error(sprintf('[_.sprintf] property "%s" does not exist', match[2][k]));
  33. }
  34. arg = arg[match[2][k]];
  35. }
  36. } else if (match[1]) { // positional argument (explicit)
  37. arg = argv[match[1]];
  38. }
  39. else { // positional argument (implicit)
  40. arg = argv[cursor++];
  41. }
  42. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  43. throw new Error(sprintf('[_.sprintf] expecting number but found %s', get_type(arg)));
  44. }
  45. switch (match[8]) {
  46. case 'b': arg = arg.toString(2); break;
  47. case 'c': arg = String.fromCharCode(arg); break;
  48. case 'd': arg = parseInt(arg, 10); break;
  49. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  50. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  51. case 'o': arg = arg.toString(8); break;
  52. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  53. case 'u': arg = Math.abs(arg); break;
  54. case 'x': arg = arg.toString(16); break;
  55. case 'X': arg = arg.toString(16).toUpperCase(); break;
  56. }
  57. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  58. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  59. pad_length = match[6] - String(arg).length;
  60. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  61. output.push(match[5] ? arg + pad : pad + arg);
  62. }
  63. }
  64. return output.join('');
  65. };
  66. str_format.cache = {};
  67. str_format.parse = function(fmt) {
  68. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  69. while (_fmt) {
  70. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  71. parse_tree.push(match[0]);
  72. }
  73. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  74. parse_tree.push('%');
  75. }
  76. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  77. if (match[2]) {
  78. arg_names |= 1;
  79. var field_list = [], replacement_field = match[2], field_match = [];
  80. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  81. field_list.push(field_match[1]);
  82. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  83. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  84. field_list.push(field_match[1]);
  85. }
  86. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  87. field_list.push(field_match[1]);
  88. }
  89. else {
  90. throw new Error('[_.sprintf] huh?');
  91. }
  92. }
  93. }
  94. else {
  95. throw new Error('[_.sprintf] huh?');
  96. }
  97. match[2] = field_list;
  98. }
  99. else {
  100. arg_names |= 2;
  101. }
  102. if (arg_names === 3) {
  103. throw new Error('[_.sprintf] mixing positional and named placeholders is not (yet) supported');
  104. }
  105. parse_tree.push(match);
  106. }
  107. else {
  108. throw new Error('[_.sprintf] huh?');
  109. }
  110. _fmt = _fmt.substring(match[0].length);
  111. }
  112. return parse_tree;
  113. };
  114. return str_format;
  115. })();
  116. module.exports = sprintf;