Simulate C # Lambda Methods in Javascript

I would like to simulate a C # Any () method that can be used to determine if a collection has any matching objects based on a lambda expression.

I used jQuery $. grep to simplify the task:

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('xa === 1')); //true console.log(foo.any('xa === 2')); //false 

I know that eval() is bad practice for obvious reasons. But is it normal in this case, since I will not use it with anything related to some user inputs?

Can this be done without eval() ? I cannot figure out a way to pass an expression to a function without evaluating it.

http://jsfiddle.net/dgGvN/

+6
source share
2 answers

I suggest you take a look at closing JS. In particular, what you did there can be done initially in JS using the Array.some method:

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

edit: in this case we do not use closure, but simple simple anonymous functions ...

+9
source

Pass function:

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

Source: https://habr.com/ru/post/944981/


All Articles