Dans un groupe, il y a des étudiants [👩🏼🦰👦🏿👨🦱👨🏽🦳👩🏽🧔🏽 👩🏽 ]avec chacun une moyenne.
Comment écrire que l'on recherche s'il existe un.E étudiant.e abscent (ABI)
→ Réponse mySome(students, isABI);
Dans un panier (basket) 🧺, il y a plein de fruits et des légumes 🍍🍑 🥕🍅🥦🍒🍌🥔🍄🍓🧄🌰🫛.
Comment écrire que l'on recherche s'il existe un fruit sans pépin (seed) ?
→ Réponse mySome(basket, isSeedlessFruit);
🪛En action
const basket = [
{ icon: "🍎", hasSeeds: true, color: "red", price: 1.2, category: "fruit" },
{
icon: "🥕",
hasSeeds: false,
color: "orange",
price: 0.7,
category: "vegetable",
},
{
icon: "🍌",
hasSeeds: false,
color: "yellow",
price: 1.0,
category: "fruit",
},
{
icon: "🥦",
hasSeeds: false,
color: "green",
price: 1.8,
category: "vegetable",
},
{ icon: "🍓", hasSeeds: true, color: "red", price: 0.5, category: "fruit" },
{
icon: "🍆",
hasSeeds: true,
color: "purple",
price: 2.1,
category: "vegetable",
},
{ icon: "🥝", hasSeeds: true, color: "green", price: 1.3, category: "fruit" },
{
icon: "🍍",
hasSeeds: false,
color: "yellow",
price: 3.5,
category: "fruit",
},
];
const isSeedlessFruit = basketItem =>
basketItem.category === "fruit" && !basketItem.hasSeeds;
const hasSeedlessFruit = mySome(basket, isSeedlessFruit);
/**
* Custom implementation of Array.prototype.some()
* ------------------------------------------------
* @param {Array} array - the list we want to check
* @param {Function} fxn - the test function applied to each element
* @returns {boolean} - true if at least one element passes the test
*
* How it works:
* - Loop through the array
* - Apply the callback to each element
* - If the callback returns true → stop and return true
* - If no element matches → return false
*/
function mySome(array, fxn) {
for (let i = 0; i < array.length; i++) {
if (fxn(array[i],i,array)) {
return true; // Found at least one matching item
}
}
return false; // No match found
}