Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

334
Views
Equivalente a Enumerable.First de LINQ (predicado)

En C#, tenemosEnumerable.First(predicate) . Dado este código 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); }

aparte de forEach , usando loop, usando múltiples o operadores o llamando implícitamente a some(predicate) , ¿hay una forma más inteligente de encontrar firstMatch ? Preferiblemente, una función de JavaScript (algo así como filterFirst(pedicate) ) que provoca un cortocircuito en la primera coincidencia que se asemeja a la implementación Enumerable.First() de C#.

FWIW, estoy apuntando a los tiempos de ejecución de node.js / io.js.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

No es necesario reinventar la rueda, la forma correcta de hacerlo es usar .find :

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

Si está utilizando un navegador que no es compatible .find , puede polillenarlo

over 4 years ago · Santiago Trujillo Report

0

Los usuarios de LINQ llaman a first y firstOrDefault muchas veces sin predicado, lo que no es posible con find . Asi que,

 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 Report

0

Puede emular esto en el caso de que desee devolver el primer valor real con reduce .

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

editar: hecho más conciso con la sugerencia de @BenjaminGruenbaum

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!