1 | /** |
---|
2 | * sprintf() for JavaScript v.0.1 |
---|
3 | * |
---|
4 | * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/> |
---|
5 | * |
---|
6 | * This program is free software; you can redistribute it and/or modify it under |
---|
7 | * the terms of the GNU General Public License as published by the Free Software |
---|
8 | * Foundation; either version 2 of the License, or (at your option) any later |
---|
9 | * version. |
---|
10 | * |
---|
11 | * This program is distributed in the hope that it will be useful, but WITHOUT |
---|
12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
---|
13 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more |
---|
14 | * details. |
---|
15 | * |
---|
16 | * You should have received a copy of the GNU General Public License along with |
---|
17 | * this program; if not, write to the Free Software Foundation, Inc., 59 Temple |
---|
18 | * Place, Suite 330, Boston, MA 02111-1307 USA |
---|
19 | */ |
---|
20 | |
---|
21 | function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); } |
---|
22 | |
---|
23 | function sprintf() { |
---|
24 | var i = 0, f = arguments[i++], o = [], m, a, p; |
---|
25 | while (f) { |
---|
26 | if (m = /^[^\x25]+/.exec(f)) o.push(m[0]); |
---|
27 | else if (m = /^\x25{2}/.exec(f)) o.push('%'); |
---|
28 | else if (m = /^\x25(\+)?(0|'[^$])?(-)?(\d+)?(\.\d+)?([b-fosuxX])/.exec(f)) { |
---|
29 | if (!(a = arguments[i++])) throw("Too few arguments."); |
---|
30 | if (/[^s]/.test(m[6]) && (typeof(a) != 'number')) |
---|
31 | throw("Expecting number but found " + typeof(a)); |
---|
32 | switch (m[6]) { |
---|
33 | case 'b': a = a.toString(2); break; |
---|
34 | case 'c': a = String.fromCharCode(a); break; |
---|
35 | case 'd': a = parseInt(a); break; |
---|
36 | case 'e': a = m[5] ? a.toExponential(m[5].charAt(1)) : a.toExponential(); break; |
---|
37 | case 'f': a = m[5] ? parseFloat(a).toFixed(m[5].charAt(1)) : parseFloat(a); break; |
---|
38 | case 'o': a = a.toString(8); break; |
---|
39 | case 's': a = ((a = String(a)) && m[5] ? a.substring(0, m[5].charAt(1)) : a); break; |
---|
40 | case 'u': a = Math.abs(a); break; |
---|
41 | case 'x': a = a.toString(16); break; |
---|
42 | case 'X': a = a.toString(16).toUpperCase(); break; |
---|
43 | } |
---|
44 | a = (/[def]/.test(m[6]) && m[1] && a > 0 ? '+' + a : a); |
---|
45 | p = m[4] ? str_repeat(m[2] ? m[2] == '0' ? '0' : m[2].charAt(1) : ' ', m[5] ? m[4] - String(a).length : m[4]) : ''; |
---|
46 | o.push(m[3] ? a + p : p + a); |
---|
47 | } else throw("Huh ?"); |
---|
48 | f = f.substring(m[0].length); |
---|
49 | } |
---|
50 | return(o.join('')); |
---|
51 | } |
---|