0

I would like to pass a comparer into a function and not sure if this is possible with Javascript. There is an IComparer concept in C# that does this. Can this be done in Javascript?

function someAction (comparer) {
    var newList = [];
        $.each(list, function (index, item) {
            if comparer on item is true then { //psuedo code
                newList.push(item);
            }
        });
}

someAction(item.PropA > 5);
TruMan1
  • 33,665
  • 59
  • 184
  • 335

3 Answers3

4

function someAction (comparer) {
    var newList = [];
        $.each(list, function (index, item) {
            if (comparer(item)) {
                newList.push(item);
            }
        });
}
someAction(function (item) { return item.PropA > 5 });

PS: as @BrokenGlass suggested, you can avoid reinventing the wheel and use the filter function.

akonsu
  • 28,824
  • 33
  • 119
  • 194
0

Just call the function:

  if (comparer(item)) { ... }

All references to functions in JavaScript are equivalent, so any reference can be used to invoke a function in the same way any other reference can be used. Functions are first-class objects, in other words.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

You might be looking for filter, which already exists in JavaScript:

var newList = list.filter(function(item) {
  return item.PropA > 5;
});
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335