PageRenderTime 121ms CodeModel.GetById 0ms RepoModel.GetById 1ms app.codeStats 0ms

/library/sprintf.js

http://pyjamas.googlecode.com/
JavaScript | 57 lines | 51 code | 3 blank | 3 comment | 47 complexity | 5ec31497a46ed1ff0f4f9a222caaa19b MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0
  1. // args is a pyjslib_List
  2. // str is a String
  3. function sprintf(str, args)
  4. {
  5. if(args && args.__class__ != "pyjslib_List")
  6. args = new pyjslib_List([args]);
  7. if (!args || pyjslib_len(args) < 1 || !RegExp)
  8. {
  9. return;
  10. }
  11. var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
  12. var a = b = [], numSubstitutions = 0, numMatches = 0;
  13. while (a = re.exec(str))
  14. {
  15. var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
  16. var pPrecision = a[5], pType = a[6], rightPart = a[7];
  17. //alert(a + '\n' + [a[0], leftpart, pPad, pJustify, pMinLength, pPrecision);
  18. numMatches++;
  19. if (pType == '%')
  20. {
  21. subst = '%';
  22. }
  23. else
  24. {
  25. if (numSubstitutions >= args.length)
  26. {
  27. alert('Error! Not enough function args (' + (args.length - 1) + ', excluding the string)\nfor the number of substitution parameters in string (' + numSubstitutions + ' so far).');
  28. }
  29. var param = args.__getitem__(numSubstitutions);
  30. var pad = '';
  31. if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
  32. else if (pPad) pad = pPad;
  33. var justifyRight = true;
  34. if (pJustify && pJustify === "-") justifyRight = false;
  35. var minLength = -1;
  36. if (pMinLength) minLength = parseInt(pMinLength);
  37. var precision = -1;
  38. if (pPrecision && pType == 'f') precision = parseInt(pPrecision.substring(1));
  39. var subst = param;
  40. if (pType == 'b') subst = parseInt(param).toString(2);
  41. else if (pType == 'c') subst = String.fromCharCode(parseInt(param));
  42. else if (pType == 'd') subst = parseInt(param) ? parseInt(param) : 0;
  43. else if (pType == 'u') subst = Math.abs(param);
  44. else if (pType == 'f') subst = (precision > -1) ? Math.round(parseFloat(param) * Math.pow(10, precision)) / Math.pow(10, precision): parseFloat(param);
  45. else if (pType == 'o') subst = parseInt(param).toString(8);
  46. else if (pType == 's') subst = param;
  47. else if (pType == 'x') subst = ('' + parseInt(param).toString(16)).toLowerCase();
  48. else if (pType == 'X') subst = ('' + parseInt(param).toString(16)).toUpperCase();
  49. numSubstitutions++;
  50. }
  51. str = leftpart + subst + rightPart;
  52. }
  53. return str;
  54. }