-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
Copy pathexpand_properties.js
74 lines (59 loc) · 2.17 KB
/
expand_properties.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
import EmberError from 'ember-metal/error';
/**
@module ember
@submodule ember-metal
*/
var SPLIT_REGEX = /\{|\}/;
var END_WITH_EACH_REGEX = /\.@each$/;
/**
Expands `pattern`, invoking `callback` for each expansion.
The only pattern supported is brace-expansion, anything else will be passed
once to `callback` directly.
Example
```js
function echo(arg){ console.log(arg); }
Ember.expandProperties('foo.bar', echo); //=> 'foo.bar'
Ember.expandProperties('{foo,bar}', echo); //=> 'foo', 'bar'
Ember.expandProperties('foo.{bar,baz}', echo); //=> 'foo.bar', 'foo.baz'
Ember.expandProperties('{foo,bar}.baz', echo); //=> 'foo.baz', 'bar.baz'
Ember.expandProperties('foo.{bar,baz}.[]', echo) //=> 'foo.bar.[]', 'foo.baz.[]'
Ember.expandProperties('{foo,bar}.{spam,eggs}', echo) //=> 'foo.spam', 'foo.eggs', 'bar.spam', 'bar.eggs'
Ember.expandProperties('{foo}.bar.{baz}') //=> 'foo.bar.baz'
```
@method expandProperties
@for Ember
@private
@param {String} pattern The property pattern to expand.
@param {Function} callback The callback to invoke. It is invoked once per
expansion, and is passed the expansion.
*/
export default function expandProperties(pattern, callback) {
if (pattern.indexOf(' ') > -1) {
throw new EmberError(`Brace expanded properties cannot contain spaces, e.g. 'user.{firstName, lastName}' should be 'user.{firstName,lastName}'`);
}
if ('string' === typeof pattern) {
var parts = pattern.split(SPLIT_REGEX);
var properties = [parts];
parts.forEach((part, index) => {
if (part.indexOf(',') >= 0) {
properties = duplicateAndReplace(properties, part.split(','), index);
}
});
properties.forEach((property) => {
callback(property.join('').replace(END_WITH_EACH_REGEX, '.[]'));
});
} else {
callback(pattern.replace(END_WITH_EACH_REGEX, '.[]'));
}
}
function duplicateAndReplace(properties, currentParts, index) {
var all = [];
properties.forEach((property) => {
currentParts.forEach((part) => {
var current = property.slice(0);
current[index] = part;
all.push(current);
});
});
return all;
}