-
Notifications
You must be signed in to change notification settings - Fork 36
/
index.js
332 lines (319 loc) · 9.95 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
void function(global) {
'use strict';
// ValueError :: String -> Error
function ValueError(message) {
var err = new Error (message);
err.name = 'ValueError';
return err;
}
// create :: Object -> String,*... -> String
function create(transformers) {
return function(template) {
var args = Array.prototype.slice.call (arguments, 1);
var idx = 0;
var state = 'UNDEFINED';
return template.replace (
/([{}])\1|[{](.*?)(?:!(.+?))?[}]/g,
function(match, literal, _key, xf) {
if (literal != null) {
return literal;
}
var key = _key;
if (key.length > 0) {
if (state === 'IMPLICIT') {
throw ValueError ('cannot switch from ' +
'implicit to explicit numbering');
}
state = 'EXPLICIT';
} else {
if (state === 'EXPLICIT') {
throw ValueError ('cannot switch from ' +
'explicit to implicit numbering');
}
state = 'IMPLICIT';
key = String (idx);
idx += 1;
}
// 1. Split the key into a lookup path.
// 2. If the first path component is not an index, prepend '0'.
// 3. Reduce the lookup path to a single result. If the lookup
// succeeds the result is a singleton array containing the
// value at the lookup path; otherwise the result is [].
// 4. Unwrap the result by reducing with '' as the default value.
var path = key.split ('.');
var value = (/^\d+$/.test (path[0]) ? path : ['0'].concat (path))
.reduce (function(maybe, key) {
return maybe.reduce (function(_, x) {
return x != null && key in Object (x) ?
[typeof x[key] === 'function' ? x[key] () : x[key]] :
[];
}, []);
}, [args])
.reduce (function(_, x) { return x; }, '');
if (xf == null) {
return value;
} else if (Object.prototype.hasOwnProperty.call (transformers, xf)) {
return transformers[xf] (value);
} else {
throw ValueError ('no transformer named "' + xf + '"');
}
}
);
};
}
// format :: String,*... -> String
var format = create ({});
// format.create :: Object -> String,*... -> String
format.create = create;
// format.extend :: Object,Object -> ()
format.extend = function(prototype, transformers) {
var $format = create (transformers);
prototype.format = function() {
var args = Array.prototype.slice.call (arguments);
args.unshift (this);
return $format.apply (global, args);
};
};
/* istanbul ignore else */
if (typeof module !== 'undefined') {
module.exports = format;
} else if (typeof define === 'function' && define.amd) {
define (function() { return format; });
} else {
global.format = format;
}
/* istanbul ignore if */
if (typeof __doctest !== 'undefined') {
format.extend (String.prototype, {});
}
//. # string-format
//.
//. string-format is a small JavaScript library for formatting strings,
//. based on Python's [`str.format()`][1]. For example:
//.
//. ```javascript
//. > const user = {
//. . firstName: 'Jane',
//. . lastName: 'Smith',
//. . email: '[email protected]',
//. . }
//. ```
//.
//. ```javascript
//. > '"{firstName} {lastName}" <{email}>'.format (user)
//. '"Jane Smith" <[email protected]>'
//. ```
//.
//. The equivalent concatenation:
//.
//. ```javascript
//. > '"' + user.firstName + ' ' + user.lastName + '" <' + user.email + '>'
//. '"Jane Smith" <[email protected]>'
//. ```
//.
//. ### Installation
//.
//. #### Node
//.
//. 1. Install:
//.
//. ```console
//. $ npm install string-format
//. ```
//.
//. 2. Require:
//.
//. ```javascript
//. const format = require ('string-format')
//. ```
//.
//. #### Browser
//.
//. 1. Define `window.format`:
//.
//. ```html
//. <script src="path/to/string-format.js"></script>
//. ```
//.
//. ### Modes
//.
//. string-format can be used in two modes: [function mode](#function-mode)
//. and [method mode](#method-mode).
//.
//. #### Function mode
//.
//. ```javascript
//. > format ('Hello, {}!', 'Alice')
//. 'Hello, Alice!'
//. ```
//.
//. In this mode the first argument is a template string and the remaining
//. arguments are values to be interpolated.
//.
//. #### Method mode
//.
//. ```javascript
//. > 'Hello, {}!'.format ('Alice')
//. 'Hello, Alice!'
//. ```
//.
//. In this mode values to be interpolated are supplied to the `format`
//. method of a template string. This mode is not enabled by default.
//. The method must first be defined via [`format.extend`](#format.extend):
//.
//. ```javascript
//. > format.extend (String.prototype, {})
//. ```
//.
//. `format (template, $0, $1, …, $N)` and `template.format ($0, $1, …, $N)`
//. can then be used interchangeably.
//.
//. <a name="format"></a>
//.
//. ### `format (template, $0, $1, …, $N)`
//.
//. Returns the result of replacing each `{…}` placeholder in the template
//. string with its corresponding replacement.
//.
//. Placeholders may contain numbers which refer to positional arguments:
//.
//. ```javascript
//. > '{0}, you have {1} unread message{2}'.format ('Holly', 2, 's')
//. 'Holly, you have 2 unread messages'
//. ```
//.
//. Unmatched placeholders produce no output:
//.
//. ```javascript
//. > '{0}, you have {1} unread message{2}'.format ('Steve', 1)
//. 'Steve, you have 1 unread message'
//. ```
//.
//. A format string may reference a positional argument multiple times:
//.
//. ```javascript
//. > "The name's {1}. {0} {1}.".format ('James', 'Bond')
//. "The name's Bond. James Bond."
//. ```
//.
//. Positional arguments may be referenced implicitly:
//.
//. ```javascript
//. > '{}, you have {} unread message{}'.format ('Steve', 1)
//. 'Steve, you have 1 unread message'
//. ```
//.
//. A format string must not contain both implicit and explicit references:
//.
//. ```javascript
//. > 'My name is {} {}. Do you like the name {0}?'.format ('Lemony', 'Snicket')
//. ! ValueError: cannot switch from implicit to explicit numbering
//. ```
//.
//. `{{` and `}}` in format strings produce `{` and `}`:
//.
//. ```javascript
//. > '{{}} creates an empty {} in {}'.format ('dictionary', 'Python')
//. '{} creates an empty dictionary in Python'
//. ```
//.
//. Dot notation may be used to reference object properties:
//.
//. ```javascript
//. > const bobby = {firstName: 'Bobby', lastName: 'Fischer'}
//. > const garry = {firstName: 'Garry', lastName: 'Kasparov'}
//.
//. > '{0.firstName} {0.lastName} vs. {1.firstName} {1.lastName}'.format (bobby, garry)
//. 'Bobby Fischer vs. Garry Kasparov'
//. ```
//.
//. `0.` may be omitted when referencing a property of `{0}`:
//.
//. ```javascript
//. > const repo = {owner: 'davidchambers', slug: 'string-format'}
//.
//. > 'https://github.com/{owner}/{slug}'.format (repo)
//. 'https://github.com/davidchambers/string-format'
//. ```
//.
//. If the referenced property is a method, it is invoked with no arguments
//. to determine the replacement:
//.
//. ```javascript
//. > const sheldon = {
//. . firstName: 'Sheldon',
//. . lastName: 'Cooper',
//. . dob: new Date ('1970-01-01'),
//. . fullName: function() { return this.firstName + ' ' + this.lastName },
//. . quip: function() { return 'Bazinga!' },
//. . }
//.
//. > '{fullName} was born at precisely {dob.toISOString}'.format (sheldon)
//. 'Sheldon Cooper was born at precisely 1970-01-01T00:00:00.000Z'
//.
//. > "I've always wanted to go to a goth club. {quip.toUpperCase}".format (sheldon)
//. "I've always wanted to go to a goth club. BAZINGA!"
//. ```
//.
//. <a name="format.create"></a>
//.
//. ### `format.create (transformers)`
//.
//. This function takes an object mapping names to transformers and returns
//. a formatting function. A transformer is applied if its name appears,
//. prefixed with `!`, after a field name in a template string.
//.
//. ```javascript
//. > const fmt = format.create ({
//. . escape: s =>
//. . s.replace (/[&<>"'`]/g, c => '&#' + c.charCodeAt (0) + ';'),
//. . upper: s =>
//. . s.toUpperCase (),
//. . })
//.
//. > fmt ('Hello, {!upper}!', 'Alice')
//. 'Hello, ALICE!'
//.
//. > fmt ('<a href="{url!escape}">{name!escape}</a>', {
//. . name: 'Anchor & Hope',
//. . url: 'http://anchorandhopesf.com/',
//. . })
//. '<a href="http://anchorandhopesf.com/">Anchor & Hope</a>'
//. ```
//.
//. <a name="format.extend"></a>
//.
//. ### `format.extend (prototype, transformers)`
//.
//. This function takes a prototype (presumably `String.prototype`) and an
//. object mapping names to transformers, and defines a `format` method on
//. the prototype. A transformer is applied if its name appears, prefixed
//. with `!`, after a field name in a template string.
//.
//. ```javascript
//. > format.extend (String.prototype, {
//. . escape: s =>
//. . s.replace (/[&<>"'`]/g, c => '&#' + c.charCodeAt (0) + ';'),
//. . upper: s =>
//. . s.toUpperCase (),
//. . })
//.
//. > 'Hello, {!upper}!'.format ('Alice')
//. 'Hello, ALICE!'
//.
//. > '<a href="{url!escape}">{name!escape}</a>'.format ({
//. . name: 'Anchor & Hope',
//. . url: 'http://anchorandhopesf.com/',
//. . })
//. '<a href="http://anchorandhopesf.com/">Anchor & Hope</a>'
//. ```
//.
//. ### Running the test suite
//.
//. ```console
//. $ npm install
//. $ npm test
//. ```
//.
//. [1]: http://docs.python.org/library/stdtypes.html#str.format
}.call (this, this);