Soy un poco novato de JS y actualmente estoy tratando de aprender funciones de matriz.
Al intentar refactorizar parte de mi antiguo código, me topé con esto:
export const determineValue = (events) => { let eligible = false for (const event of events) { if (event.eventType === "1") { eligible = true } else if (event.eventType === "2") { eligible = false return eligible } } return eligible } Para este caso, "1" y "2" son los únicos valores posibles de event.eventType .
¿Cómo puedo escribir esto de forma compacta?
¿Hay mejores prácticas a considerar aquí?
Gracias de antemano por cualquier aclaración!
Una solución simplificada sería
//example setup const events = [{"eventType":"1"},{"eventType":"2"}]; // Solution const eventTypes = events.map(x => x.eventType); return eventTypes.includes("1") && !eventTypes.includes("2");Yo iría con algo como esto:
const determineValue = (events) => { return events.length > 0 && !(events.every(input => input.eventType === "2")); } Si events.length > 0 es falso, la parte detrás de && no se ejecuta y la función devuelve inmediatamente false .
De lo contrario, comprueba si cada elemento de los events tiene un valor "2" para su propiedad eventType . Devuelve false si la comprobación tiene éxito y true si falla, debido al ! en frente de eso.
const events0 =[]; const events1 =[{eventType: "1"}, {eventType: "2"}, {eventType: "1"}]; const events2 =[{eventType: "2"}, {eventType: "2"}, {eventType: "2"}]; const determineValue = (events) => { return events.length > 0 && !(events.every(input => input.eventType === "2")); } console.log(determineValue(events0)); console.log(determineValue(events1)); console.log(determineValue(events2));Dado que los eventos elegibles son de tipo 1, todo lo que necesita hacer es filtrar la matriz de eventos para esos y luego devolver la longitud de la matriz filtrada.
const events =[{eventType: 1},{eventType: 1},{eventType: 2},{eventType: 2},{eventType: 1},{eventType: 1}]; const determineValue = (events) => { return events.filter(x => x.eventType === 1).length } ; console.log(determineValue(events)); // gives 4 events are type 1 console.log(events.length); // gives 6 events in totalPara mejorarlo, también puede pasar el tipo que desea contar (en caso de que desee contar los eventos no elegibles en su lugar)
const events =[{eventType: 1},{eventType: 1},{eventType: 2},{eventType: 2},{eventType: 1},{eventType: 1}]; const determineValue = (events, value) => { return events.filter(x => x.eventType === value).length } ; console.log(determineValue(events, 1)); // gives 4 events are type 1 console.log(determineValue(events, 2)); //gives 2 events are type 2 console.log(events.length); // gives 6 events in total