Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

335
Visualizações
Equivalent to LINQ's Enumerable.First(predicate)

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

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?

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

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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

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

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

over 4 years ago · Santiago Trujillo Relatório

0

LINQ users call first and firstOrDefault a lot with no predicate, which is not possible with find. So,

  first() {
    var firstOrDefault = this.firstOrDefault();
    if(firstOrDefault !== undefined)
      return firstOrDefault;
    else
      throw new Error('No element satisfies the condition in predicate.');
  }

  firstOrDefault() {
    return this.find(o => true);
  }
over 4 years ago · Santiago Trujillo Relatório

0

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

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

edit: made more terse with @BenjaminGruenbaum suggestion

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda