forked from kangax/protolicious
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset_builder.js
40 lines (35 loc) · 1.19 KB
/
set_builder.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
/**
* SetBuilder(expression[, context = this]) -> *
* - expression(String): expression to evaluate
* - scope(Object): context to evaluate expression within
*
* var numbers = [1,2,3,4,5,6,7,8,9];
*
* var lessThanFive = numbers.findAll(function(n) { return n<5 });
* // vs
* var lessThanFive = SetBuilder('x | x <- numbers, x<5');
*
* var moreThanFiveSquare = numbers.findAll(function(n) { return n>5 }).map(function(n) { return n*n });
* // or
* var moreThanFiveSquare = numbers.inject([], function(result, n) { if (n>5) result.push(n); return result });
* // vs
* var moreThanFiveSquare = SetBuilder('x*x | x <- numbers, x>5');
*
*/
function SetBuilder(expr, context) {
var re = /([^|]*)\|([^<]*)<-([^,]*),([^$]*)$/,
match = expr.match(re),
id, action, source, condition, results = [];
if (!match)
throw new SyntaxError('Error parsing expression');
match = match.invoke('strip');
id = match[2];
source = match[3];
action = match[1].replace(id, '_', 'g');
condition = match[4].replace(id, '_', 'g');
(context || this)[source].each(function(_) {
if (eval(condition))
results.push(eval(action))
})
return results;
}