| |
1 /* This Source Code Form is subject to the terms of the Mozilla Public |
| |
2 * License, v. 2.0. If a copy of the MPL was not distributed with this |
| |
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| |
4 |
| |
5 String.prototype.format = function string_format() { |
| |
6 // there are two modes of operation... unnamed indices are read in order; |
| |
7 // named indices using %(name)s. The two styles cannot be mixed. |
| |
8 // Unnamed indices can be passed as either a single argument to this function, |
| |
9 // multiple arguments to this function, or as a single array argument |
| |
10 let curindex = 0; |
| |
11 let d; |
| |
12 |
| |
13 if (arguments.length > 1) { |
| |
14 d = arguments; |
| |
15 } |
| |
16 else |
| |
17 d = arguments[0]; |
| |
18 |
| |
19 function r(s, key, type) { |
| |
20 if (type == '%') |
| |
21 return '%'; |
| |
22 |
| |
23 let v; |
| |
24 if (key == "") { |
| |
25 if (curindex == -1) |
| |
26 throw Error("Cannot mix named and positional indices in string formatting."); |
| |
27 |
| |
28 if (curindex == 0 && (!(d instanceof Object) || !(0 in d))) { |
| |
29 v = d; |
| |
30 } |
| |
31 else if (!(curindex in d)) |
| |
32 throw Error("Insufficient number of items in format, requesting item %i".format(curindex)); |
| |
33 else { |
| |
34 v = d[curindex]; |
| |
35 } |
| |
36 |
| |
37 ++curindex; |
| |
38 } |
| |
39 else { |
| |
40 key = key.slice(1, -1); |
| |
41 if (curindex > 0) |
| |
42 throw Error("Cannot mix named and positional indices in string formatting."); |
| |
43 curindex = -1; |
| |
44 |
| |
45 if (!(key in d)) |
| |
46 throw Error("Key '%s' not present during string substitution.".format(key)); |
| |
47 v = d[key]; |
| |
48 } |
| |
49 switch (type) { |
| |
50 case "s": |
| |
51 if (v === undefined) |
| |
52 return "<undefined>"; |
| |
53 return v.toString(); |
| |
54 case "r": |
| |
55 return uneval(v); |
| |
56 case "i": |
| |
57 return parseInt(v); |
| |
58 case "f": |
| |
59 return Number(v); |
| |
60 default: |
| |
61 throw Error("Unexpected format character '%s'.".format(type)); |
| |
62 } |
| |
63 } |
| |
64 return this.replace(/%(\([^)]+\))?(.)/g, r); |
| |
65 }; |