Browse files

document evil SetBuilder

  • Loading branch information...
1 parent 9a6e68f commit a0eef4387d00da3daedc0dccc28932a61aed66ac kangax committed Apr 13, 2008
Showing with 26 additions and 27 deletions.
  1. +26 −27 set_builder.js
View
53 set_builder.js
@@ -1,30 +1,28 @@
-/*
-
-
-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');
-
-
-*/
-
-SetBuilder = function(expr, scope) {
- var scope = scope || this,
- re = /([^|]*)\|([^<]*)<-([^,]*),([^$]*)$/,
+/**
+ * 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 });
@foca
foca added a note Apr 13, 2008

It should actually be push(n*n), right?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ * // 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 Error('Error parsing expression');
+ if (!match)
+ throw new SyntaxError('Error parsing expression');
match = match.invoke('strip');
@@ -33,9 +31,10 @@ SetBuilder = function(expr, scope) {
action = match[1].replace(id, '_', 'g');
condition = match[4].replace(id, '_', 'g');
- scope[source].each(function(_) {
- if (eval(condition)) results.push(eval(action))
+ (context || this)[source].each(function(_) {
+ if (eval(condition))
+ results.push(eval(action))
})
-
+
return results;
}

1 comment on commit a0eef43

@kangax
Owner

@foca
yep : )
I’ll fix that as soon as I get a chance

Please sign in to comment.