1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/config/string-format.js Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,65 @@ 1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.7 + 1.8 +String.prototype.format = function string_format() { 1.9 + // there are two modes of operation... unnamed indices are read in order; 1.10 + // named indices using %(name)s. The two styles cannot be mixed. 1.11 + // Unnamed indices can be passed as either a single argument to this function, 1.12 + // multiple arguments to this function, or as a single array argument 1.13 + let curindex = 0; 1.14 + let d; 1.15 + 1.16 + if (arguments.length > 1) { 1.17 + d = arguments; 1.18 + } 1.19 + else 1.20 + d = arguments[0]; 1.21 + 1.22 + function r(s, key, type) { 1.23 + if (type == '%') 1.24 + return '%'; 1.25 + 1.26 + let v; 1.27 + if (key == "") { 1.28 + if (curindex == -1) 1.29 + throw Error("Cannot mix named and positional indices in string formatting."); 1.30 + 1.31 + if (curindex == 0 && (!(d instanceof Object) || !(0 in d))) { 1.32 + v = d; 1.33 + } 1.34 + else if (!(curindex in d)) 1.35 + throw Error("Insufficient number of items in format, requesting item %i".format(curindex)); 1.36 + else { 1.37 + v = d[curindex]; 1.38 + } 1.39 + 1.40 + ++curindex; 1.41 + } 1.42 + else { 1.43 + key = key.slice(1, -1); 1.44 + if (curindex > 0) 1.45 + throw Error("Cannot mix named and positional indices in string formatting."); 1.46 + curindex = -1; 1.47 + 1.48 + if (!(key in d)) 1.49 + throw Error("Key '%s' not present during string substitution.".format(key)); 1.50 + v = d[key]; 1.51 + } 1.52 + switch (type) { 1.53 + case "s": 1.54 + if (v === undefined) 1.55 + return "<undefined>"; 1.56 + return v.toString(); 1.57 + case "r": 1.58 + return uneval(v); 1.59 + case "i": 1.60 + return parseInt(v); 1.61 + case "f": 1.62 + return Number(v); 1.63 + default: 1.64 + throw Error("Unexpected format character '%s'.".format(type)); 1.65 + } 1.66 + } 1.67 + return this.replace(/%(\([^)]+\))?(.)/g, r); 1.68 +};