Debian Codegraph @

closure-library/closure/goog/string/stringformat.js

raw
1 // Copyright 2008 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Implementation of sprintf-like, python-%-operator-like,
17 * .NET-String.Format-like functionality. Uses JS string's replace method to
18 * extract format specifiers and sends those specifiers to a handler function,
19 * which then, based on conversion type part of the specifier, calls the
20 * appropriate function to handle the specific conversion.
21 * For specific functionality implemented, look at formatRe below, or look
22 * at the tests.
23 */
24
25 goog.provide('goog.string.format');
26
27 goog.require('goog.string');
28
29
30 /**
31 * Performs sprintf-like conversion, i.e. puts the values in a template.
32 * DO NOT use it instead of built-in conversions in simple cases such as
33 * 'Cost: %.2f' as it would introduce unnecessary latency opposed to
34 * 'Cost: ' + cost.toFixed(2).
35 * @param {string} formatString Template string containing % specifiers.
36 * @param {...string|number} var_args Values formatString is to be filled with.
37 * @return {string} Formatted string.
38 */
39 goog.string.format = function(formatString, var_args) {
40
41 // Convert the arguments to an array (MDC recommended way).
42 var args = Array.prototype.slice.call(arguments);
43
44 // Try to get the template.
45 var template = args.shift();
46 if (typeof template == 'undefined') {
47 throw new Error('[goog.string.format] Template required');
48 }
49
50 // This re is used for matching, it also defines what is supported.
51 var formatRe = /%([0\-\ \+]*)(\d+)?(\.(\d+))?([%sfdiu])/g;
52
53 /**
54 * Chooses which conversion function to call based on type conversion
55 * specifier.
56 * @param {string} match Contains the re matched string.
57 * @param {string} flags Formatting flags.
58 * @param {string} width Replacement string minimum width.
59 * @param {string} dotp Matched precision including a dot.
60 * @param {string} precision Specifies floating point precision.
61 * @param {string} type Type conversion specifier.
62 * @param {string} offset Matching location in the original string.
63 * @param {string} wholeString Has the actualString being searched.
64 * @return {string} Formatted parameter.
65 */
66 function replacerDemuxer(
67 match, flags, width, dotp, precision, type, offset, wholeString) {
68 // The % is too simple and doesn't take an argument.
69 if (type == '%') {
70 return '%';
71 }
72
73 // Try to get the actual value from parent function.
74 var value = args.shift();
75
76 // If we didn't get any arguments, fail.
77 if (typeof value == 'undefined') {
78 throw new Error('[goog.string.format] Not enough arguments');
79 }
80
81 // Patch the value argument to the beginning of our type specific call.
82 arguments[0] = value;
83
84 return goog.string.format.demuxes_[type].apply(null, arguments);
85 }
86
87 return template.replace(formatRe, replacerDemuxer);
88 };
89
90
91 /**
92 * Contains various conversion functions (to be filled in later on).
93 * @private {!Object}
94 */
95 goog.string.format.demuxes_ = {};
96
97
98 /**
99 * Processes %s conversion specifier.
100 * @param {string} value Contains the formatRe matched string.
101 * @param {string} flags Formatting flags.
102 * @param {string} width Replacement string minimum width.
103 * @param {string} dotp Matched precision including a dot.
104 * @param {string} precision Specifies floating point precision.
105 * @param {string} type Type conversion specifier.
106 * @param {string} offset Matching location in the original string.
107 * @param {string} wholeString Has the actualString being searched.
108 * @return {string} Replacement string.
109 */
110 goog.string.format.demuxes_['s'] = function(
111 value, flags, width, dotp, precision, type, offset, wholeString) {
112 var replacement = value;
113 // If no padding is necessary we're done.
114 // The check for '' is necessary because Firefox incorrectly provides the
115 // empty string instead of undefined for non-participating capture groups,
116 // and isNaN('') == false.
117 if (isNaN(width) || width == '' || replacement.length >= Number(width)) {
118 return replacement;
119 }
120
121 // Otherwise we should find out where to put spaces.
122 if (flags.indexOf('-', 0) > -1) {
123 replacement = replacement +
124 goog.string.repeat(' ', Number(width) - replacement.length);
125 } else {
126 replacement = goog.string.repeat(' ', Number(width) - replacement.length) +
127 replacement;
128 }
129 return replacement;
130 };
131
132
133 /**
134 * Processes %f conversion specifier.
135 * @param {string} value Contains the formatRe matched string.
136 * @param {string} flags Formatting flags.
137 * @param {string} width Replacement string minimum width.
138 * @param {string} dotp Matched precision including a dot.
139 * @param {string} precision Specifies floating point precision.
140 * @param {string} type Type conversion specifier.
141 * @param {string} offset Matching location in the original string.
142 * @param {string} wholeString Has the actualString being searched.
143 * @return {string} Replacement string.
144 */
145 goog.string.format.demuxes_['f'] = function(
146 value, flags, width, dotp, precision, type, offset, wholeString) {
147
148 var replacement = value.toString();
149
150 // The check for '' is necessary because Firefox incorrectly provides the
151 // empty string instead of undefined for non-participating capture groups,
152 // and isNaN('') == false.
153 if (!(isNaN(precision) || precision == '')) {
154 replacement = parseFloat(value).toFixed(precision);
155 }
156
157 // Generates sign string that will be attached to the replacement.
158 var sign;
159 if (Number(value) < 0) {
160 sign = '-';
161 } else if (flags.indexOf('+') >= 0) {
162 sign = '+';
163 } else if (flags.indexOf(' ') >= 0) {
164 sign = ' ';
165 } else {
166 sign = '';
167 }
168
169 if (Number(value) >= 0) {
170 replacement = sign + replacement;
171 }
172
173 // If no padding is necessary we're done.
174 if (isNaN(width) || replacement.length >= Number(width)) {
175 return replacement;
176 }
177
178 // We need a clean signless replacement to start with
179 replacement = isNaN(precision) ? Math.abs(Number(value)).toString() :
180 Math.abs(Number(value)).toFixed(precision);
181
182 var padCount = Number(width) - replacement.length - sign.length;
183
184 // Find out which side to pad, and if it's left side, then which character to
185 // pad, and set the sign on the left and padding in the middle.
186 if (flags.indexOf('-', 0) >= 0) {
187 replacement = sign + replacement + goog.string.repeat(' ', padCount);
188 } else {
189 // Decides which character to pad.
190 var paddingChar = (flags.indexOf('0', 0) >= 0) ? '0' : ' ';
191 replacement =
192 sign + goog.string.repeat(paddingChar, padCount) + replacement;
193 }
194
195 return replacement;
196 };
197
198
199 /**
200 * Processes %d conversion specifier.
201 * @param {string} value Contains the formatRe matched string.
202 * @param {string} flags Formatting flags.
203 * @param {string} width Replacement string minimum width.
204 * @param {string} dotp Matched precision including a dot.
205 * @param {string} precision Specifies floating point precision.
206 * @param {string} type Type conversion specifier.
207 * @param {string} offset Matching location in the original string.
208 * @param {string} wholeString Has the actualString being searched.
209 * @return {string} Replacement string.
210 */
211 goog.string.format.demuxes_['d'] = function(
212 value, flags, width, dotp, precision, type, offset, wholeString) {
213 return goog.string.format.demuxes_['f'](
214 parseInt(value, 10) /* value */, flags, width, dotp, 0 /* precision */,
215 type, offset, wholeString);
216 };
217
218
219 // These are additional aliases, for integer conversion.
220 goog.string.format.demuxes_['i'] = goog.string.format.demuxes_['d'];
221 goog.string.format.demuxes_['u'] = goog.string.format.demuxes_['d'];