JavaScript過濾器首先等同於LINQ的Enumberable.First(謂詞)

[英]JavaScript filter first equivalent to LINQ's Enumberable.First(predicate)


In C#, we have Enumerable.First(predicate). Given this JavaScript code:

在C#中,我們有Enumerable.First(謂詞)。鑒於此JavaScript代碼:

function process() {
  var firstMatch = ['a', 'b', 'c'].filter(function(e) {
    return applyConditions(e);
  }).shift();

  if(!firstMatch) {
    return;
  }

  // do something else
}

function applyConditions(element) {
  var min = 97;
  var max = 122;

  var random = Math.floor(Math.random() * (max - min + 1) + min);

  return element === String.fromCharCode(random);
}

other than forEach, using loop, using multiple or operators or implicitly calling some(predicate), is there a smarter way of finding the firstMatch? Preferably a JavaScript function (something like filterFirst(pedicate)) which short-circuits on first match resembling C#'s Enumerable.First() implementation?

除了forEach,使用循環,使用多個或運算符或隱式調用某些(謂詞),是否有更聰明的方法來查找firstMatch?最好是一個JavaScript函數(類似filterFirst(pedicate)),它在第一次匹配時短路,類似於C#的Enumerable.First()實現?

FWIW, I am targeting node.js / io.js runtimes.

FWIW,我的目標是node.js / io.js運行時。

3 个解决方案

#1


35  

No need to reinvent the wheel, the correct way to do it is to use .find:

無需重新發明輪子,正確的方法是使用.find:

var firstMatch = ['a', 'b', 'c'].find(applyConditions);

If you're using a browser that does not support .find you can polyfill it

如果您使用的瀏覽器不支持.find,您可以將其填充

#2


2  

You could emulate this in the case where you want to return the first truthy value with reduce.

您可以在想要使用reduce返回第一個truthy值的情況下模擬這個。

['a', 'b', 'c'].reduce(function(prev, curr) { 
    return prev || predicate(curr) && curr; 
}, false);

edit: made more terse with @BenjaminGruenbaum suggestion

編輯:@BenjaminGruenbaum建議更加簡潔

#3


1  

Sorry but this is trivial as hell

對不起,這對於地獄來說是微不足道的

function first(array, predicate) {
    for (var i = 0; i < array.length; ++i) {
        if (predicate(array[i])) return array[i];
    }
    throw new Error("no match");
}

It's ok to create your own abstractions people.

可以創建自己的抽象人員。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/02/12/725af5a08fd480279393e1c3d8b857d4.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com