Affichage des articles dont le libellé est reduce. Afficher tous les articles
Affichage des articles dont le libellé est reduce. Afficher tous les articles

Algo : comparaisons

 let tab = [1, 2, 3, -1, 6, 6, 1, 2, 2, 1];

let i = 0;
while (i < tab.length) {
  let j = i + 1;
  while (j < tab.length) {
    if (tab[i] === tab[j]) {
      // Swap elements
      [tab[i + 1], tab[j]] = [tab[j], tab[i + 1]];
      i++;
    }
    j++;
  }
  i++;
}

[ 1, 1, 1, -1, 6, 6, 2, 2, 2, 3 ]

let groups = tab.reduce((acc, num) => {
  acc[num] = acc[num] || [];
  acc[num].push(num);
  return acc;
}, {});

let result = [].concat(...Object.values(groups));

console.log(result);

┌─────────┬────────┐ │ (index) │ Values │ ├─────────┼────────┤ │ 0 │ 1 │ │ 1 │ 1 │ │ 2 │ 1 │ │ 3 │ 2 │ │ 4 │ 2 │ │ 5 │ 2 │ │ 6 │ 3 │ │ 7 │ 6 │ │ 8 │ 6 │ │ 9 │ -1 │ └─────────┴────────┘

destructuration + reduce

const dir = films.reduce( (acc, cur) => {

  acc[cur.director] = [ ... (acc[cur.director] || [] ), cur.title ];

  return acc;

}, {}); 

Reduce with Map : closest value

 let value = 610;


const table = new Map([
    [0,'yellowgreen'],
    [150, 'green'],
    [600, 'olive'],
    [750, 'red'],
    [800, 'black'],
]);

const closestKey = [...table.keys()].reduce( (acc, key) => {
   return acc = ( Math.abs(acc-value) < Math.abs(key-value) ) ? acc : key
})

┌───────────────────┬─────┬───────────────┐
│ (iteration index) │ Key │ Values │ ├───────────────────┼─────┼───────────────┤ │ 0 │ 0 │ 'yellowgreen' │ │ 1 │ 150 │ 'green' │ │ 2 │ 600 │ 'olive' │ │ 3 │ 750 │ 'red' │ │ 4 │ 800 │ 'black' │ └───────────────────┴─────┴───────────────┘ console.log(closestKey, table.get(closestKey))
// 600 olive




Map : en action

 

let value = 610;

const table = new Map([
    [0,'yellowgreen'],
    [150, 'green'],
    [600, 'olive'],
    [750, 'red'],
    [800, 'black'],
]);

console.table(table.keys());
console.table([...table.keys()]);



table.keys() renvoie un itérateur ! 
[... table.keys()] renvoie un tableau !


Reduce : sortir du reduce !

 Nous voudrions faire la somme d'un tableau jusqu'au moment où la somme dépasse une valeur

  1. const array = [1,2,3,4,5,6];
  2. const x = array.slice(0).reduce((acc, curr, i, tab) => {

  3.        if (acc>5) {
  4.            tab.splice(1);  
  5.            console.count(`tab = ${tab}`); //ne marche pas sur pythontutor
  6.            return acc;
  7.        }
  8.        console.count(`tab = ${tab}`);
  9.        return (acc += curr);
  10.     });

  11. console.log("total ", x, "\noriginal Arr: ", array);

code

Filtre


  1. const filter = 

  2.   (fx, array) => array.reduce(

  3.     (acc, item) => fx(item) ? acc.concat(item) : acc, 

  4.   []);

  5. const greaterThan4 = (x) => x >= 4;

  6. const data   = [0, 1, 2, 3, 4, 5];

  7. let result = filter(greaterThan4, data);


code

window.getComputedStyle

window.getComputedStyle donne les propriétés d'un éléments.

Remarque

Le plus grande clé peut être obtenue avec :

Math.max(...Object.keys(cssObj).map(v=>v.length))

reduce : destructuring

const liste = [
{age:10,arg:2,exp:2},
{age:1,arg:1},
{age:100,arg:3},
];

function AgeArg(acc,{arg,age}){
  return acc+ age*arg;
}

let T = liste.reduce(AgeArg,0);

console.log(T); //321

Parcours du Dom

allTag = (node) =>{

    let tag = [],
        allEle = {};


    _explore = (node) => {
      for (let elt of node.children) {
            tag.push(elt.nodeName);
            _explore(elt);
      }
    }


    _explore(node);
 
    _getWordCnt = (arr) => {
      return arr.reduce(function(prev,next){
        prev[next] = (prev[next] + 1) || 1;
        return prev;
      },{});
    }
 
    allEle = _getWordCnt(tag);

    //allEle {div:2,p:10}


    console.log(Object.keys(allEle).map(key => `${key}*${allEle[key]} `));

   console.log(`La balise la plus utilisée est : ${Object.keys(allEle).reduce((keya, keyb) =>allEle[keya] > allEle[keyb] ? keya : keyb)}`);

    let all = Object.keys(allEle).sort((keya, keyb) => allEle[keyb] - allEle[keya]);


    console.log("par ordre de présence  ** ");
    for (var b of all) {
         console.log(` ${b} ${allEle[b]} ` );
    }

 
    return allEle;


}


let a = allTag(document.body);


for (var b in a) {
  if (a.hasOwnProperty(b)) {
    console.log(`la balise ${b} apparaît ${a[b]} fois  ` );
  }
}


... en action


Voici un élégant moyen de remplacer concat.

const T1 = ["Dupont", "Whells", "toto"];

const T2 = ["Dupond", "Whells", "titi"];

console.log(T1);
console.log(...T1);
console.log( [...T1 , ...T2] );



const promos = [
  { promo: "L3miage", etudiants: ["Dupont", "Whells", "Toto"]},
  { promo: "L2miage", etudiants: ["Dupond", "Pathé"]},
  { promo: "M1miage", etudiants: ["Audu", "Baby"]},
]

const tousEtudiants = promos.reduce(function(prev, curr) {
  return [...prev, ...curr.etudiants];
},[]);

console.log(tousEtudiants.sort());

reduce

'use strict';

let t = ["abcdefghi"];

let MyA = t[0].split("");

/*
let v = MyA.reduce(function(p,n,i,array){
  //console.log(p,n,i,i%3);
  return (i%3===0) ? (p+"\n"+n) : (p+n);
});
*/

let v = MyA.reduce((p,n,i) => (i%3===0) ? (p+"\n"+n) : (p+n));
console.log(v);

fonction fléchée

Voici un cas d'écriture de fonction fléchées :

var motL = "anticonstitutionnelement myélosaccoradiculographie cyclopentanoperhydrophénanthrène intergouvernementalisation";

motT = motL.split(" ");

console.log(motT.map(el => el.length).reduce((a, b) => Math.max(a, b)));

console.log(motT.reduce((a, b) => a.length > b.length ? a : b));


Voici une utilisation sur le DOM ! 

motL = document.querySelector("div");

motT = motL.innerHTML.split(" ");

var Max = motT.reduce((a, b) => a.length > b.length ? a : b);

motL.innerHTML = motL.innerHTML.replace(Max, "<span>"+Max+"</span>");



https://jsbin.com/pasedu/edit?html,css,js,console,output

JS Bin on jsbin.com

Lire l'article suivant pour découvrir le this lexical dans les fonctions fléchées.