Pages

Cours : Map/Set

const languageSkills = [
  {
    language: "Spanish",
    skill: "Professional Proficiency",
  },
  {
    language: "English",
    skill: "Professional Working Proficiency",
  },
  {
    language: "German",
    skill: "Professional Proficiency",
  },
];



const output = languageSkills.reduce((map, { language, skill }) => {
  if (map.has(skill)) map.get(skill).push(language);
  else map.set(skill, [language]);
  return map;
}, new Map());


const nativeResult = Object.groupBy(languageSkills, (item) => item.skill);





Préparation au DS

   ...

🍕Base des données

const pizzas = [

    { name:"queen", ingredients: ["🐷","🍄","🍅","🧀"] },

    { name: "cheese", ingredients: ["🧀", "🍅"]},

    { name: "oriental", ingredients: ["🍅","🐑","🍄","🌶"]},

    { name: "royal", ingredients: ["🍅","🌵"]},

  ];

🪛 Questions

Trouvez les pizzas avec du 🧀

Trouvez les pizzas avec du 🍅

Trouvez les pizzas avec un ingrédient quelconque (soit du "🍅" ou du "🧀" ou du "🐑" ...)

Trouvez les pizzas avec au moins un ingrédient parmi une liste d'ingrédients

Trouvez les pizzas avec tous les ingrédients d'une liste

Trouvez les pizzas avec viande

Ajoutez pour chaque pizza le type (🐮ou ☘️)

Trouvez l'ensemble des ingrédients  "🐷","🍄","🍅","🧀","🐑","🌶","🌵"

Trouvez pour chaque ingrédient le nombre de pizzas l'utilisant ,"🧀":2 …

Trouvez pour chaque ingrédient la liste des pizzas l'utilisant

Ajoutez le prix de chaque pizza

prices = new Map([ ["🍅", 1], ["🐷", 2], ["🌶",2], ["🍄", 5], ["🧀", 5], ["🐑", 2], ["🌵", 10]]);

Projet : Guess

Le joueur a trois chances pour trouver un nombre secret !

💥Imaginez que vous soyez chef de projet, vous rédigez en urgence un prototype pour les membres de votre équipe. Ce prototype permet à tous de fixer les idées (proto).

👷 Il faudra l'implémenter en JS.

TD

  const pizzas = [

    { name:"queen", ingredients: ["🐷","🍄","🍅","🧀"] },

    { name: "cheese", ingredients: ["🧀", "🍅"]},

    { name: "oriental", ingredients: ["🍅","🐑","🍄","🌶"]},

    { name: "royal", ingredients: ["🍅","🌵"]},

  ];

Voici une représentation sous forme de tableau : 

🍕Questions ?

  1. Trouvez la liste des ingredients : ["🐷","🍄","🍅","🧀",🐑","🌶","🌵"]
  2. Trouvez pour chaque ingredient la liste des pizzas : 

test :

Evaluez : 

  const dataBase = [
{ name: "queen", ingredients: ["🐷", "🍄", "🍅", "🧀"] },
  { name: "cheese", ingredients: ["🧀", "🍅"] },
  { name: "oriental", ingredients: ["🍅", "🐑", "🍄", "🌶"] },
  { name: "royal", ingredients: ["🍅", "🌵"] },
];


const orientalPizza = dataBase.find( (pizza) => {
  return pizza.name==="oriental";
})
console.log(orientalPizza);

const royalPizza =
dataBase.find((pizza) => pizza.ingredients === ["🍅", "🌵"]);
console.log(royalPizza);

 const pizzas = [

    { name:"queen", ingredients: ["🐷","🍄","🍅","🧀"] },

    { name: "cheese", ingredients: ["🧀", "🍅"]},

    { name: "oriental", ingredients: ["🍅","🐑","🍄","🌶"]},

    { name: "royal", ingredients: ["🍅","🌵"]},

  ];

Voici une représentation sous forme de tableau : 

🍕Questions ?

  1. Trouvez les pizzas avec du 🧀
  2. Trouvez les pizzas avec du 🍅
  3. Trouvez les pizzas avec un ingrédient quelconque

TD : methods

 // trouvez 🚀

const getRandomArray = (length) => {
  return Array.from({ length }, () => Math.floor(Math.random() * 5));
};

getRandomArray(5); //
const arr = getRandomArray(5);

// give max
const max = Math.max( 🚀 ); //

// give max with reduce
const maxWithReduce = arr.reduce( 🚀 );

// give min and max with reduce
const minMaxWithReduce = arr.reduce(
  🚀 ,
  { min: Infinity, max: -Infinity }
);

//use destructuring to get min and max
const { 🚀 } = minMaxWithReduce;
console.log(min, maximum);

// give ocurrences of numbers in array
const occurrences = arr.reduce((acc, val) => {
  🚀 );

console.log(occurrences);

Exemple d'affichage :

Notre structure de base pour les TDs


const pizzas = [
  { name: "queen", toppings: ["🐷", "🍄", "🍅", "🧀"] },
  { name: "cheese", toppings: ["🧀", "🍅"] },
  { name: "oriental", toppings: ["🍅", "🐑", "🍄", "🌶"] },
  { name: "royal", toppings: ["🍅", "🌵"] },
];

Special event

Function Style, Method Style

 The main difference between the function style and the use of the `filter() or map()` method lies 

in the programming paradigm they represent.


🥇**Function Style**: The function style represents the procedural programming paradigm.

🎖️ **Method Style**: The method style represents the functional programming paradigm.

Création de sa propre librairie de fonctions !

 loops to methods

Mon forEach

const corbeille = ["Orange", "Banane", "Ananas", "Pamplemousse"];

1) Afficher les fruits de la corbeille de fruits.



2) Coupez les fruits en deux.

 

3) Comment utiliser cette fonction

function randomDrink(fruit, i, fruits) {
  const drinks = ["🥤", "🧋", "🍹"];
  const choice = drinks[Math.floor(Math.random() * drinks.length)];
  const article = /^[aeiou]/i.test(fruit) ? "d'" : "de ";
  fruits[i] = `${choice} ${article}${fruit}`;
}
Voici des résultats possibles

TD : foreach


 🔢 1.1 Doubling Each Number
onst numbers = [3, 7, 10, 2];
console.log(numbers); // [6, 14, 20, 4] 
🔢 1.2 Tripling Each Number
onst numbers = [3, 7, 10, 2];
console.log(numbers); // [9, 21, 30, 12]
🔢 1.3 Doubling Each Number (new array)
onst numbers = [3, 7, 10, 2];
console.log(doubled); // [6, 14, 20, 4]
---

📉 2. Finding the Maximum Value

const numbers = [15, 42, 8, 33];
console.log(`Max: ${max}`); // Max: 42

---

🧮 3. Counting Even Numbers
const numbers = [4, 9, 12, 7, 6];
console.log(`Even numbers: ${count}`); // Even numbers: 3

---

📊 4. Creating a Frequency Map
const numbers = [1, 2, 2, 3, 3, 3];
const frequency = {};
console.log(frequency); // { '1': 1, '2': 2, '3': 3 }

---

🧹 5. Cleaning or Normalizing Dat
const rawData = [102, 98, 105, 100]; console.log(normalized); // [2, -2, 5, 0]

---

📦 6. Transforming API Dat
const users = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 },
  { name: "Charlie", age: 35 }
];
console.log(names); // ["Alice", "Bob", "Charlie"]




const allTag = (rootElement) => {
  let tags = [],
    counts = {};

  const explore = (element) => {
    for (const child of element.children) {
      tags.push(child.nodeName);
      explore(child);
    }
  };

  explore(rootElement);

  const getWordCnt = (arr) => {
    return arr.reduce((acc, tag) => {
      acc[tag] = (acc[tag] || 0) + 1;
      return acc;
    }, {});
  };

  counts = getWordCnt(tags);

  const sortCounts = (obj) => {
    let sortedEntries = Object.entries(obj).sort((a, b) => b[1] - a[1]);
    // return Object.fromEntries(sortedEntries);
    return sortedEntries
  };

  return sortCounts(counts);
};

const tagCounts = allTag(document.body);
const sortedKeys = tagCounts.map((entry) => entry[0].toLowerCase());
console.log(sortedKeys);

// Create a table for displaying results
const createTable = (data) => {
  let table = document.createElement("table");
  table.style.border = "1px solid black";
  table.style.borderCollapse = "collapse";
  table.style.width = "50%";

  let headerRow = table.insertRow();
  let tagHeader = headerRow.insertCell(0);
  let countHeader = headerRow.insertCell(1);

  tagHeader.textContent = "Tag Name";
  countHeader.textContent = "Count";

  tagHeader.style.border = countHeader.style.border = "1px solid black";
  tagHeader.style.padding = countHeader.style.padding = "5px";
  tagHeader.style.fontWeight = "bold";
  countHeader.style.fontWeight = "bold";

  for (let [tag, count] of (data)) {
    let row = table.insertRow();
    let tagCell = row.insertCell(0);
    let countCell = row.insertCell(1);

    tagCell.textContent = tag;
    countCell.textContent = count;

    tagCell.style.border = countCell.style.border = "1px solid black";
    tagCell.style.padding = countCell.style.padding = "5px";
  }

  document.body.appendChild(table);
};

// Display the table
createTable(tagCounts);

help

 const tags = [

  "section",
  "article",
  "h1",
  "h2",
  "p",
  "article",
  "p",
  "p",
  "span",
  "span",
  "span",
];

//find unique tags
const uniqueTags = [...new Set(tags)];
console.log("Unique Tags using Set:", uniqueTags);

//find unique tags whitout Set
const uniqueTagsWithoutSet = tags.filter(
  (tag, index) => tags.indexOf(tag) === index
);
console.log("Unique Tags without Set:", uniqueTagsWithoutSet);

//find unique tags using reduce
const uniqueTagsUsingReduce = tags.reduce((acc, tag) => {
  if (!acc.includes(tag)) {
    acc.push(tag);
  }
  return acc;
}, []);
console.log("Unique Tags using reduce:", uniqueTagsUsingReduce);

// find occurrences of each tag using reduce
const tagOccurrences = tags.reduce((acc, tag) => {
  acc[tag] = (acc[tag] || 0) + 1;
  return acc;
}, {});
console.log("Tag Occurrences using reduce:", tagOccurrences);

// find the most frequent tag using reduce

const mostFrequentTag = Object.entries(tagOccurrences).reduce(
  (max, current) => (current[1] > max[1] ? current : max),
  ["", 0]
);
console.log("Most Frequent Tag using reduce:", mostFrequentTag);

const listOfRandomTags = ["section", "footer"];

// Check if all tags in listOfRandomTags are present in uniqueTagsUsingReduce
const allTagsPresent = listOfRandomTags.every((tag) =>
  uniqueTagsUsingReduce.includes(tag)
);
console.log("All tags present in uniqueTagsUsingReduce:", allTagsPresent);

// Check if any tag in listOfRandomTags is present in uniqueTagsUsingReduce
const anyTagPresent = listOfRandomTags.some((tag) =>
  uniqueTagsUsingReduce.includes(tag)
);

console.log("Any tag present in uniqueTagsUsingReduce:", anyTagPresent);

// groupe tagOccurrences by two values sup of occurences = 2 and less than or equal to 2

const groupedTagOccurrences = Object.entries(tagOccurrences).reduce(
  (acc, [tag, count]) => {
    if (count > 2) {
      acc.moreThanTwo.push({ tag, count });
    } else {
      acc.twoOrLess.push({ tag, count });
    }
    return acc;
  },
  { moreThanTwo: [], twoOrLess: [] }
);
console.log("Grouped Tag Occurrences:", groupedTagOccurrences);