diff options
Diffstat (limited to 'js/sprintf.js')
-rw-r--r-- | js/sprintf.js | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/js/sprintf.js b/js/sprintf.js new file mode 100644 index 0000000..4d61fa2 --- /dev/null +++ b/js/sprintf.js | |||
@@ -0,0 +1,78 @@ | |||
1 | /** | ||
2 | * | ||
3 | * This program is free software; you can redistribute it and/or modify it | ||
4 | * under the terms of the GNU General Public License as published by the Free | ||
5 | * Software Foundation; either version 2 of the License, or (at your option) | ||
6 | * any later version. | ||
7 | * | ||
8 | * This program is distributed in the hope that it will be useful, but WITHOUT | ||
9 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | ||
10 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for | ||
11 | * more details. | ||
12 | |||
13 | * You should have received a copy of the GNU General Public License along | ||
14 | * with this program; if not, write to the Free Software Foundation, Inc., | ||
15 | * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA | ||
16 | |||
17 | **/ | ||
18 | |||
19 | "use strict"; | ||
20 | |||
21 | function sprintf() | ||
22 | { | ||
23 | var argc = 0; | ||
24 | var args = arguments; | ||
25 | var fmt = args[argc++]; | ||
26 | |||
27 | function lpad (str, padString, length) | ||
28 | { | ||
29 | while (str.length < length) | ||
30 | str = padString + str; | ||
31 | return str; | ||
32 | }; | ||
33 | |||
34 | function format (match, width, dot, precision, length, conversion) | ||
35 | { | ||
36 | if (match === '%%') return '%'; | ||
37 | |||
38 | var value = args[argc++]; | ||
39 | var prefix; | ||
40 | |||
41 | if (width === undefined) | ||
42 | width = 0; | ||
43 | else | ||
44 | width = +width; | ||
45 | |||
46 | if (precision === undefined) | ||
47 | precision = conversion == 'd' ? 0 : 6; | ||
48 | else | ||
49 | precision = +precision; | ||
50 | |||
51 | switch (conversion) { | ||
52 | case 's': | ||
53 | case 'c': | ||
54 | return value; | ||
55 | break; | ||
56 | case 'd': | ||
57 | return parseInt(value, 10); | ||
58 | break; | ||
59 | case 'e': | ||
60 | prefix = value < 0 ? '-' : ''; | ||
61 | return lpad(prefix+Math.abs(value).toExponential(precision),' ',width); | ||
62 | break; | ||
63 | case 'F': | ||
64 | case 'f': | ||
65 | prefix = value < 0 ? '-' : ''; | ||
66 | return lpad(prefix+Math.abs(value).toFixed(precision),' ',width); | ||
67 | break; | ||
68 | case 'g': | ||
69 | prefix = value < 0 ? '-' : ''; | ||
70 | return lpad(prefix+Math.abs(value).toPrecision(precision),' ',width); | ||
71 | break; | ||
72 | default: | ||
73 | return match; | ||
74 | } | ||
75 | |||
76 | }; | ||
77 | return fmt.replace(/%(\d+)?(\.(\d+))?(l?)([%scdfFeg])/g,format); | ||
78 | }; | ||