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