Backed out changeset fa432b23baa5. (Backing out bug 454781 to investigate mochitest...
[wine-gecko.git] / xpcom / analysis / string-format.js
blob70632211986b6294ca16cc66016ce8a429071eb9
1 String.prototype.format = function string_format() {
2 // there are two modes of operation... unnamed indices are read in order;
3 // named indices using %(name)s. The two styles cannot be mixed.
4 // Unnamed indices can be passed as either a single argument to this function,
5 // multiple arguments to this function, or as a single array argument
6 let curindex = 0;
7 let d;
9 if (arguments.length > 1) {
10 d = arguments;
12 else
13 d = arguments[0];
15 function r(s, key, type) {
16 let v;
17 if (key == "") {
18 if (curindex == -1)
19 throw Error("Cannot mix named and positional indices in string formatting.");
21 if (curindex == 0 && (!(d instanceof Object) || !(0 in d))) {
22 v = d;
24 else if (!(curindex in d))
25 throw Error("Insufficient number of items in format, requesting item %i".format(curindex));
26 else {
27 v = d[curindex];
30 ++curindex;
32 else {
33 key = key.slice(1, -1);
34 if (curindex > 0)
35 throw Error("Cannot mix named and positional indices in string formatting.");
36 curindex = -1;
38 if (!(key in d))
39 throw Error("Key '%s' not present during string substitution.".format(key));
40 v = d[key];
42 switch (type) {
43 case "s":
44 if (v === undefined)
45 return "<undefined>";
46 return v.toString();
47 case "r":
48 return uneval(v);
49 case "i":
50 return parseInt(v);
51 case "f":
52 return Number(v);
53 case "%":
54 return "%";
55 default:
56 throw Error("Unexpected format character '%s'.".format(type));
59 return this.replace(/%(\([^)]+\))?(.)/g, r);