Pages

rotation de matrice !

code


const t = [

  [0,1,0],

  [1,1,1],

  ]


const rev = t => t[0].map( (_,i) =>  t.map( r => r[i]).reverse());


  

const aff = t => {

  const text = t

    .map(row => [...row].join(" "))

    .join("\n");

  return text;

};


console.log(aff(rev(t)))

algo

 >>> separe([1, 0, 1, 0, 1, 0, 1, 0]) 

[0, 0, 0, 0, 1, 1, 1, 1]

Algo 1


đŸ€ĄAlgo 2


😡Algo 3


Algo 4

filtre and co 3

const products = [

  {
    "_id": 1,
    "item": "abc",
    "price": 10,
    "quantity": 2,
    "date": "2014-03-01T08:00:00.000Z"
  },
  {
    "_id": 2,
    "item": "jkl",
    "price": 20,
    "quantity": 1,
    "date": "2014-03-01T09:00:00.000Z"
  },
  {
    "_id": 3,
    "item": "xyz",
    "price": 5,
    "quantity": 10,
    "date": "2014-03-15T09:00:00.000Z"
  },
  {
    "_id": 4,
    "item": "xyz",
    "price": 5,
    "quantity": 20,
    "date": "2014-04-04T11:21:39.736Z"
  },
  {
    "_id": 5,
    "item": "abc",
    "price": 10,
    "quantity": 10,
    "date": "2014-04-04T21:23:13.331Z"
  },
  {
    "_id": 6,
    "item": "def",
    "price": 7.5,
    "quantity": 5,
    "date": "2015-06-04T05:08:13.000Z"
  },
  {
    "_id": 7,
    "item": "def",
    "price": 7.5,
    "quantity": 10,
    "date": "2015-09-10T08:43:00.000Z"
  },
  {
    "_id": 8,
    "item": "abc",
    "price": 10,
    "quantity": 5,
    "date": "2016-02-06T20:20:13.000Z"
  }
]

function date(min,max){

  return function( {date} ){
    if (new Date(min) <= new Date(date) && new Date(date) <= new Date(max)) {return true}
    else {return false}
  }


}


const myagg = function(acc, cur)  {
  if (!acc[cur.item]) acc[cur.item] = 0;
  acc[cur.item]+=cur.price*cur.quantity;
  return acc
}

const filtre = products.filter(date('2014-01-01','2015-01-01'))
                       .reduce( myagg,{})

console.log(filtre)

const result = []
for (const [key, value] of Object.entries(filtre)) {
  // console.log(`${key}, ${value}`);
  result.push(
    {
      "_id": key,
      "totalSaleAmount": value
    }
  )
}
console.table(result)

filtre and co 2

function date(min,max){
  return function( {date} ){
    if (new Date(min) <= new Date(date) && new Date(date) <= new Date(max)) {return true}
    else {return false}
  }
}

const myagg = function(acc, cur)  {
  if (!acc[cur.item]) acc[cur.item] = 0;
  acc[cur.item]+=cur.price*cur.quantity;
  return acc
}

const filtre = products.filter(date('2014-01-01','2015-01-01'))
                       .reduce( myagg,{})
console.log(filtre)


code 

filtre & co 1

 const products = [

  {
    "_id": 1,
    "item": "abc",
    "price": 10,
    "quantity": 2,
    "date": "2014-03-01T08:00:00.000Z"
  },
  {
    "_id": 2,
    "item": "jkl",
    "price": 20,
    "quantity": 1,
    "date": "2014-03-01T09:00:00.000Z"
  },
  {
    "_id": 3,
    "item": "xyz",
    "price": 5,
    "quantity": 10,
    "date": "2014-03-15T09:00:00.000Z"
  },
  {
    "_id": 4,
    "item": "xyz",
    "price": 5,
    "quantity": 20,
    "date": "2014-04-04T11:21:39.736Z"
  },
  {
    "_id": 5,
    "item": "abc",
    "price": 10,
    "quantity": 10,
    "date": "2014-04-04T21:23:13.331Z"
  },
  {
    "_id": 6,
    "item": "def",
    "price": 7.5,
    "quantity": 5,
    "date": "2015-06-04T05:08:13.000Z"
  },
  {
    "_id": 7,
    "item": "def",
    "price": 7.5,
    "quantity": 10,
    "date": "2015-09-10T08:43:00.000Z"
  },
  {
    "_id": 8,
    "item": "abc",
    "price": 10,
    "quantity": 5,
    "date": "2016-02-06T20:20:13.000Z"
  }
]

function date(min,max){

  return function( {date} ){
    if (new Date(min) <= new Date(date) && new Date(date) <= new Date(max)) {return true}
    else {return false}
  }


}

const filtre = products.filter(date('2014-04-01','2015-01-01'))

Adetruire

<!DOCTYPE html>

<html lang="en">


<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

    <style>

        html {

            scroll-behavior: smooth;

        }


        #partie_definition {

            background-color: yellow;

        }

    </style>

</head>


<body>

    <a href="./About/aboutme.html">About me</a>

    <a href="https://www.ibisc.univ-evry.fr/~dupont/" target="_blank">Dupont</a>

    <a href="./Images/47.jpg" download>me</a>

    <a href="#partie_definition">definition</a>

    <a href="mailto:denis.dupont@univ.fr">email</a>

    <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nesciunt quae a earum minus officia. Quam, neque? Ea

        nulla nisi dolore laudantium quia tenetur saepe maiores veniam consequuntur vel ab fugit 

        consectetur, ex quasi distinctio nihil laborum consequuntur animi qui! Fuga repudiandae necessitatibus

        reiciendis fugiat eos cumque!</p>

    <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Saepe exercitationem incidunt quam at beatae adipisci

        aspernatur error et, odio itaque nam mollitia voluptas veritatis eveniet odit excepturi temporibus accusantiu

        aspernatur vel eum cum porro numquam magni. Ipsum harum dolorum nisi deleniti blanditiis fugiat pariatur aut

        ipsa nesciunt dolore! Autem cumque dignissimos saepe nihil eveniet sequi soluta pariatur dolor neque?</p>

    <p id="partie_definition">Lorem ipsum dolor sit amet consectetur adipisicing elit. Iste provident repellendus ipsam.

        Eos mollitia



        veritatis praesentium temporibus! Velit beatae incidunt voluptatum sunt, culpa laboriosam quia fuga at.</p>


    <a href="#">Top</a>

</body>


</html> 

filtre, map ...

Le chaßnage des filtres élémentaires

const population = [

    { nom: "Dupont"ville: "evry"sex: "f"born: 1970 },
    { nom: "Dupont"ville: "Paris"sex: "f"born: 1980 },
    { nom: "Brusel"ville: "belfort"sex: "h"born: 1969 },
    { nom: "SuperDupont"ville: "Evry"sex: "f"born: 1971 },
    { nom: "Leroy"ville: "Paris"sex: "f"born: 1984 },
    { nom: "Tony"ville: "belfort"sex: "h"born: 2000 },

];

//definitions pour filtre

const setAge = (pers=> {
    let age = new Date().getFullYear() - pers.born;
    return Object.assign(pers, { age });
}
const people = population.map(setAge),
femme = {
     genre: "f"
},
     homme = {
        genre: "h"
     },
     cinquante = {
        age: 50,
    },
    quarante = {
        age: 40,
    },
    Ă‰vryens = {
        ville: "evry",
    },

    genre = function ({ sex }) {
        return sex == this.genre;
    },

    trancheAge = function ({ age }) {
        return age > this.age;
    },

    habitant = function ({ ville }) {
        return ville.toLowerCase() == this.ville.toLowerCase();
    },


// on peut filtrer maintenant sans effort
    
    f50 = people.filter(genrefemme)
         .filter(trancheAgecinquante),

    h50 = people.filter(genrehomme)
         .filter(trancheAgequarante),

evryC19 = people.filter(habitantÉvryens)
        .filter(trancheAgecinquante)
         .filter(genrehomme);

 lien


Les filtres dans un tableaux !

Il est intéressant de mettre des fonctions dans des tableaux :
  1. const pipeline = [
  2.   function A,
  3.   function B, ...
  4. ];
  5. for( let action of pipeline) {
  6.    objet = action( objet );
  7. }
L'intĂ©rĂȘt du code est en lig. 6 : Chaque actions renvoie l'objet pour l'action suivante.

👿Cette technique est à la base des filtres de Photoshop.

Voici un exemple de chainage d'actions sur un point. Code

Appliquons ce principe sur nos filtres avec la gĂ©niale utilisation de la mĂ©thode every en lig.2.
  1. const customFilter = (array, ...queries=> {
  2.    return array.filter( pers => queries.every( query => query(pers) ));
  3. },
  4.         
  5. resultQuery = customFilter(population,
  6.             ( { nom } ) => nom == "SuperDupont",
  7.             ( { born } ) => new Date().getFullYear() - born > 40,
  8.             ( { sex  } ) => sex == "f",
  9.             ( { ville} ) => ville == "evry"
  10.         );



👍 AmĂ©liorations

  1. const customFilter = (array, ...tests) => {
  2.     return array.filter(pers => tests.every(t => t(pers)));
  3. }

  4. const filtre = (query) =>
  5. customFilter(population,
  6.      ( {nom} )    => query.nom ? nom.toLowerCase() == query.nom : true,
  7.      ( { born } ) => query.born ? new Date().getFullYear() - born > query.born : true,
  8.      ( { sex }  ) => query.sex ? sex == query.sex : true,
  9.      ( { ville }) => query.ville ? ville.toLowerCase() == query.ville : true
  10. );

  11. const firstQuery = {
  12.    nom:"dupont",
  13.    born:40,
  14.    sex:"f",
  15.    ville:"paris",
  16. }

  17. console.log(filtre (firstQuery))

  18. const Evryens = {
  19.    ville:"evry",
  20. }

  21. console.log(filtre (Evryens))

                                                  đŸ’ȘA step futher, 

                                                  Pour ceux qui n'auraient pas lu " avoid using bind "

                                                  notez lig.7 la présence de bind.


                                                  1. nom =   function ( {nom} )  { return nom.toLowerCase() == this.nom },
                                                  2. age =   function ( { born } ) { return new Date().getFullYear() - born > this.born},
                                                  3. genre = function ( { sex }  ) { return sex == this.sex},
                                                  4. habite =function ( { ville }) { return ville.toLowerCase() == this.ville},

                                                  5. customFilter = (array, query, ...tests) => {
                                                  6.     return array.filter(pers => tests.every(t => t.bind(query)(pers)));
                                                  7. }

                                                  8. const myQuery = {
                                                  9.    nom:"dupont",
                                                  10.    born:40,
                                                  11.    sex:"f",
                                                  12.    ville:"paris",  
                                                  13. }
                                                  14. const query1 = customFilter(population, myQuery, nom,age,genre,habite);
                                                  15. console.log(query1);

                                                  16. const query2 = customFilter(population, myQuery, habite);
                                                  17. console.log(query2)

                                                  test : flex

                                                   Donner le code CSS Ă  Ă©crire dans le simulateur (donner en dessous) pour obtenir les cinq figures suivantes.


                                                  Par exemple pour la figure suivante :
                                                  on pourrait écrire :
                                                  .flex-conteneur { display :flex; padding : 10px 0; } .flex-conteneur *{ flex : 100%; }









                                                  Utiliser le simulateur ! 





                                                  1
                                                  2

                                                  TD 4 : charger la solution depuis gitHub

                                                   Voici quelques indication pour tĂ©lĂ©charger le dĂ©pĂŽt depuis github ( lien )

                                                  event


                                                  <!DOCTYPE html>
                                                  <html lang="en">
                                                  <head>
                                                  <meta charset="utf-8"/>
                                                  <title>Show Event properties</title>

                                                  <style>
                                                  table { border-collapse: collapse; }
                                                  thead { font-weight: bold; }
                                                  td { padding: 2px 10px 2px 10px; }

                                                  .odd { background-color: #efdfef; }
                                                  .even { background-color: #ffffff; }
                                                  </style>

                                                  <script>

                                                  function showEventProperties(e) {
                                                    console.log("entre");
                                                    function addCell(row, text) {
                                                      var cell = row.insertCell(-1);
                                                      cell.appendChild(document.createTextNode(text));
                                                    }

                                                    var e = e || window.event;
                                                    document.getElementById('eventType').innerHTML = e.type;

                                                    var table = document.getElementById('tab');
                                                    table.innerHTML=""; //reset
                                                    var thead = table.createTHead();
                                                    var row = thead.insertRow(-1);
                                                    var lableList = ['#', 'Property', 'Value'];
                                                    var len = lableList.length;

                                                    for (var i=0; i<len; i++) {
                                                      addCell(row, lableList[i]);
                                                    }

                                                    var tbody = document.createElement('tbody');
                                                    table.appendChild(tbody);

                                                    for (var p in e) {
                                                      row = tbody.insertRow(-1);
                                                      row.className = (row.rowIndex % 2)? 'odd':'even';
                                                      addCell(row, row.rowIndex);
                                                      addCell(row, p);
                                                      addCell(row, e[p]);
                                                    }

                                                    document.body.appendChild(table);
                                                  }

                                                  window.onload = function(event){
                                                    //showEventProperties(event);
                                                  }
                                                  </script>
                                                  </head>

                                                  <body>
                                                  <h1>Properties of the DOM <span id="eventType"></span> Event Object</h1>
                                                  <table id="tab"></table> 
                                                  <script>
                                                    var elem = document.getElementById('eventType').parentElement;
                                                    //elem.addEventListener("mouseenter", showEventProperties, false);
                                                    elem.addEventListener("mouseleave", showEventProperties, false);
                                                    //elem.addEventListener("mousemove", showEventProperties, false);
                                                    elem.addEventListener("click", showEventProperties, false);
                                                  </script>

                                                  </body>

                                                  </html>

                                                  le scroll

                                                  Les propriĂ©tĂ©s scrollTop et scrollLeft peuvent ĂȘtre manipuler



                                                  Sous le pont Mirabeau coule La Seine Et nos amours Faut il Qu'il m'en Souvienne
                                                  Voici une ref : https://javascript.info/size-and-scroll#scrollleft-scrolltop


                                                  bind en action

                                                  class GameLoop {
                                                    constructor(options) {
                                                      this.options = options;
                                                      this.running = false;
                                                      this.raf = null;
                                                      this.delta = 1000;
                                                      this.accumulator = 0;
                                                      this.last = performance.now();
                                                    }

                                                    start() {
                                                      if (!this.running) {
                                                        this.running = true;
                                                        this.raf = window.requestAnimationFrame(this.tick.bind(this));
                                                        console.log(this.raf);
                                                      }
                                                    }
                                                    stop() {
                                                      this.running = false;
                                                      window.cancelAnimationFrame(this.raf);
                                                     
                                                    }
                                                    tick() {
                                                      let now = performance.now();
                                                      let dt = now - this.last;
                                                      this.last = now;

                                                      this.accumulator += dt;


                                                      while (this.accumulator >= this.delta) {
                                                        if (this.options.render) {
                                                          this.options.render();
                                                        }

                                                        this.accumulator -= this.delta;
                                                      }

                                                      if (true && this.options.update) {
                                                        this.options.update(this.accumulator);
                                                      }

                                                      if (this.running) {
                                                        this.raf = requestAnimationFrame(this.tick.bind(this));
                                                      }
                                                    }
                                                  }

                                                  let render = function() {
                                                    const posts = [];
                                                    const random = (min, max) => Math.floor(Math.random() * (max - min)) + min
                                                    for (let i = 0; i < 1000; i++) {
                                                      posts.push({
                                                        id: `ID_${i}`,
                                                        upVotes: random(1, 1000)
                                                      });
                                                    }


                                                    console.time("sort after");
                                                    let [c, d] = posts
                                                      .reduce((acc, cur) => [cur, ...acc], [])
                                                      .sort((a, b) => b.upVotes - a.upVotes)
                                                      .slice(0, 2);
                                                    console.timeEnd("sort after");

                                                  }
                                                  update = (v) => console.log(v);

                                                  options = {
                                                    render,
                                                  }

                                                  let g = new GameLoop(options);
                                                  g.start();
                                                  window.setTimeout(g.stop,5000);

                                                  Impossible d’arrĂȘter la boucle du jeu ?
                                                  trouver la faille !


                                                  lodash

                                                  1. function baseProperty(key) {    
                                                  2.     return function (object) {        
                                                  3.         return object == null ? undefined : object[key];    
                                                  4.     };
                                                  5. }
                                                  6. let length = baseProperty('length');
                                                  7. console.log(length("denis"));
                                                  code

                                                  La closure

                                                  En lançant le deboggeur dans VS. on découvre la mise en place d'une closure.



                                                  Return function en action !

                                                  1. function baseProperty(key) {    
                                                  2.     return function (object) {        
                                                  3.         return object == null ? undefined : object[key];    
                                                  4.     };
                                                  5. }
                                                  6. let length = baseProperty('length');
                                                  7. console.log(length("denis"));
                                                  code

                                                  La closure

                                                  En lançant le deboggeur dans VS. on découvre la mise en place d'une closure.



                                                  MAX, MIN

                                                  const data = [];

                                                  const random = (min, max) => Math.floor(Math.random() * (max - min)) + min;

                                                  for (let i = 0; i < 10000; i++) {
                                                      data.push({ x: random(11000000) });
                                                  }

                                                  console.time("sort");   
                                                  const sortData = data.sort( (a,b) => b.x - a.x);
                                                  console.timeEnd("sort");
                                                  console.log(sortData.filter(i => i.x === sortData[0].x));

                                                  console.time("map");    
                                                  const mapData = data.map(i => i.x);
                                                  const maxData = Math.max(...mapData);
                                                  console.timeEnd("map");

                                                  console.log(mapData.filter(i => i === maxData));

                                                  $ node comparaisonsSortMinMax.js sort: 26.683ms [ { x: 999953 } ] map: 2.196ms [ 999953 ] $ node comparaisonsSortMinMax.js sort: 30.439ms [ { x: 999958 } ] map: 2.159ms [ 999958 ]

                                                  Map en action


                                                  1. function alphabetRange (start, end, step = 1) {
                                                  2.   return new Array(Math.ceil((end.charCodeAt(0) - start.charCodeAt(0))/step))
                                                  3.   .fill(start.charCodeAt(0))
                                                  4.   .map((x, i) => String.fromCharCode(i*step + start.charCodeAt(0)));
                                                  5. }

                                                  6. console.log(alphabetRange('c', 'h', 2));

                                                  String in action


                                                  1. let s = 'abcdefghijklmnopqrstuvwxyz'

                                                  2. s= s.substring(s.indexOf('p'), s.indexOf('t')+ 1);
                                                  3. let  A= s.split('');  




                                                  code