jquery - Simulate C# Lambda methods in Javascript -


i simulate c# any() method, can used determine whether if collection has matching objects based on lambda expression.

i used jquery's $.grep make things easier:

array.prototype.any = function (expr) {      if (typeof jquery === 'undefined')         throw new referenceerror('jquery not loaded');      return $.grep(this, function (x, i) {         return eval(expr);     }).length > 0;  };  var foo = [{ a: 1, b: 2 }, { a:1, b: 3 }];  console.log(foo.any('x.a === 1')); //true console.log(foo.any('x.a === 2')); //false 

i know eval() bad practice obvious reasons. ok in case, since won't use related user inputs?

can done without eval()? can't figure out way pass expression function without evaluating it.

http://jsfiddle.net/dggvn/

i suggest take @ js closures. in particular, did there can done natively in js using array.some method:

[{ a: 1, b: 2 }, { a:1, b: 3 }].some(function(x) { return x.a === 1; }); // true [{ a: 1, b: 2 }, { a:1, b: 3 }].some(function(x) { return x.a === 2; }); // false 

edit: in case we're not using closures rather plain simple anonymous functions...


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -