-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathutils.js
139 lines (115 loc) · 2.48 KB
/
utils.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
/**
* Module dependencies.
*/
var debug = require('debug')('reactive:utils');
//var props = require('props');
/**
* Function cache.
*/
var cache = {};
/**
* Return possible properties of a string
* @param {String} str
* @return {Array} of properties found in the string
* @api private
*/
var props = function(str) {
return str
.replace(/\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g, '')
.match(/[a-zA-Z_]\w*([.][a-zA-Z_]\w*)*/g)
|| [];
};
/**
* Return interpolation property names in `str`,
* for example "{foo} and {bar}" would return
* ['foo', 'bar'].
*
* @param {String} str
* @return {Array}
* @api private
*/
exports.interpolationProps = function(str) {
var m;
var arr = [];
var re = /\{([^}]+)\}/g;
while (m = re.exec(str)) {
var expr = m[1];
arr = arr.concat(props(expr));
}
return unique(arr);
};
/**
* Interpolate `str` with the given `fn`.
*
* @param {String} str
* @param {Function} fn
* @return {String}
* @api private
*/
exports.interpolate = function(str, fn){
return str.replace(/\{([^}]+)\}/g, function(_, expr){
var cb = cache[expr];
if (cb == null) cb = cache[expr] = compile(expr);
var val = fn(expr.trim(), cb);
return val == null ? '' : val;
});
};
/**
* Check if `str` has interpolation.
*
* @param {String} str
* @return {Boolean}
* @api private
*/
exports.hasInterpolation = function(str) {
return ~str.indexOf('{');
};
/**
* Compile `expr` to a `Function`.
*
* @param {String} expr
* @return {Function}
* @api private
*/
function compile(expr) {
var re = /\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*/g;
var p = props(expr);
// replace function calls with [ ] syntax to avoid capture as property
var funCallRe = /.\w+ *\(/g;
var body = expr.replace(funCallRe, function(_) {
return '[\'' + _.slice(1, -1) + '\'](';
});
body = body.replace(re, function(_) {
if (p.indexOf(_) >= 0) {
return access(_);
};
return _;
});
debug('compile `%s`', body);
return new Function('reactive', 'return ' + body);
}
/**
* Access a method `prop` with dot notation.
*
* @param {String} prop
* @return {String}
* @api private
*/
function access(prop) {
return 'reactive.get(\'' + prop + '\')';
}
/**
* Return unique array.
*
* @param {Array} arr
* @return {Array}
* @api private
*/
function unique(arr) {
var ret = [];
for (var i = 0; i < arr.length; i++) {
if (~ret.indexOf(arr[i])) continue;
ret.push(arr[i]);
}
return ret;
}