Bug 468916 - make modifyLogin() smarter than just remove+add. r=zpao, r=gavin
[wine-gecko.git] / config / string-format.js
blob352a5f33c58962a6ac40ef9a7ebc472663f0e70b
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 if (type == '%')
17 return '%';
19 let v;
20 if (key == "") {
21 if (curindex == -1)
22 throw Error("Cannot mix named and positional indices in string formatting.");
24 if (curindex == 0 && (!(d instanceof Object) || !(0 in d))) {
25 v = d;
27 else if (!(curindex in d))
28 throw Error("Insufficient number of items in format, requesting item %i".format(curindex));
29 else {
30 v = d[curindex];
33 ++curindex;
35 else {
36 key = key.slice(1, -1);
37 if (curindex > 0)
38 throw Error("Cannot mix named and positional indices in string formatting.");
39 curindex = -1;
41 if (!(key in d))
42 throw Error("Key '%s' not present during string substitution.".format(key));
43 v = d[key];
45 switch (type) {
46 case "s":
47 if (v === undefined)
48 return "<undefined>";
49 return v.toString();
50 case "r":
51 return uneval(v);
52 case "i":
53 return parseInt(v);
54 case "f":
55 return Number(v);
56 default:
57 throw Error("Unexpected format character '%s'.".format(type));
60 return this.replace(/%(\([^)]+\))?(.)/g, r);