like aggregation

Voici à quoi ressemble l'aggregation dans une base de données !


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"
  }
]

 const groupBy = (arr, key) =>

arr.reduce((acc, i) => {
  (acc[i[key]] = acc[i[key]] || [] ).push(i);
  return acc;
}, {});


let result = [];
let items = groupBy(products,"item");
for (const [key, value] of Object.entries(items)) {
  // console.log(`${key}, ${value}`);
  result.push(
    {
      "_id": key,
      "totalSaleAmount": value.reduce(function(acc, cur)  {
        acc+=cur.price*cur.quantity;
        return acc
      },0)
    }
  )
}
//console.table(result)
console.log(result)

Optional Chaining ?.

 


const cours = {
    titre : "JS",
    print(){
        console.log(this.titre)
    }
}

//cours.printAll() // Error
cours.printAll?.() //Optional Chaining
cours.print()

destructuration + reduce

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

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

  return acc;

}, {}); 

Remplace with regExp


html"<div> <h1> {{question}} </h1> 
<ul>
    <li>{{choice1}}</li>
    <li>{{choice2}}</li>
    <li>{{choice3}}</li>
    <li>{{choice4}}</li>
</ul>     
</div>"
randomChoise
 2
newCode"<div> <h1> {{question}} </h1> 
<ul>
    <li>{{choice1}}</li>
    <li class='selected'>{{choice2}}</li>
    <li>{{choice3}}</li>
    <li>{{choice4}}</li>
</ul>     
</div>"
const html = `<div> <h1> {{question}} </h1>
<ul>
<li>{{choice1}}</li>
<li>{{choice2}}</li>
<li>{{choice3}}</li>
<li>{{choice4}}</li>
</ul>
</div>`;
const randomChoise = (html, tagName, pos) => {
const regExp = new RegExp(`<${tagName}`, 'g');
let nbMatch = 0;
let newHTML = html.replace(regExp, function (match) {
if (nbMatch++ == pos) {
return `${match} class='selected'`
} else {
return match;
}
})
return newHTML;
}
const newCode = randomChoise(html, 'li', 2);
console.log(newCode)
view raw remplace.js hosted with ❤ by GitHub

Jest test

  https://github.com/dupontdenis/Jest-test1.git


test("Cat Boisson should has 2 articles", ()=> {
    expect(nbArtByCat.Boisson).toBe(2);
})

test("nb of Cats should be 5", ()=>{
    expect(Object.entries(nbArtByCat).length).toBe(5);
})

localstorage

 localStorage.setItem("saveTab",[1,2,3])

console.log(localStorage.getItem("saveTab")
> 1,2,3

Il faut utiliser JSON

localStorage.setItem("saveTAB",JSON.stringify([1,2,3]))


console.log(localStorage.getItem("saveTAB"))
> [1,2,3] // ce n'est pas un tableau mais un string

typeof localStorage.getItem("saveTAB")

> 'string'

Il faut utiliser JSON.parse
console.log(JSON.parse(localStorage.getItem("saveTAB")))
VM1856:1 (3) [1, 2, 3]
0: 1
1: 2
2: 3
length: 3[[Prototype]]: Array(0)

typeof JSON.parse(localStorage.getItem("saveTAB"))

'object'


En action
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="random-words.js" defer></script>
</head>
<body>
<h1>random word</h1>
<ul id="list"></ul>
</body>
</html>
view raw index.html hosted with ❤ by GitHub
//UI
const list = document.getElementById('list');
//random words
const load = async () => {
const sortable = JSON.parse(localStorage.getItem("words"))
if (!sortable) {
const data = await fetch("https://random-word-api.herokuapp.com/word?number=20");
const words = await data.json();
const alphabetical = words.reduce((a, x) => {
if (!a[x[0]]) a[x[0]] = [];
a[x[0]].push(x);
return a;
}, {});
// console.log(alphabetical)
const sortable = Object.fromEntries(
Object.entries(alphabetical).sort(([a,], [b,]) => {
if (a > b) {
return -1
} else {
return 1
}
})
);
localStorage.setItem("words", JSON.stringify(sortable));
return sortable;
} else {
return sortable;
}
}
// UI
(async () => {
const words = await load();
Object.entries(words).forEach(([letter, words]) => {
// console.log(letter, words)
const tempLi = document.createElement('li')
, tempUl = document.createElement('ul');
words.forEach((word) => tempUl.insertAdjacentHTML('afterbegin', `<li> ${word} </li>`))
tempLi.insertAdjacentElement('beforeend', tempUl)
.insertAdjacentText('beforebegin', `${letter}`)
document
.querySelector("#list")
.insertAdjacentElement('afterbegin', tempLi)
})
})()
view raw random-words.js hosted with ❤ by GitHub

RegExp

 RegExp: \d(?=(\d{3})+\.)

Un nombre suivi de 3 nombres (une ou plusieurs fois) et un point sans les consommer (?= ).

Remplacement: $& 

Correspond au chiffre \d qui correspond.

Match 10-11
Group 14-7332
Match 23-45
Group 14-7332


https://regex101.com/r/wwpOnj/1

random word

 https://random-word-api.herokuapp.com/word?number=3&length=-1


learn API 

 https://random-word-api.herokuapp.com

En action

function import

Voici une importation conditionnel à un click grâce à la fonction : 
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module" defer src="./script.js"></script>
</head>
<body>
click and see the console
</body>
</html>
view raw index.html hosted with ❤ by GitHub
export default function printModule(){
console.log("from module")
}
export function cl(){
console.log("top")
}
view raw module.js hosted with ❤ by GitHub
document.addEventListener("click", async () => {
const {default: printModule, cl } = await import("./module.js");
printModule();
cl();
console.log("from script")
});
view raw script.js hosted with ❤ by GitHub
import("./module.js");

 

Protéger un état

rappels
let u ={a:1,b:1,c:1}; u = {...u, a:2, ["b"]:2, d:2}; // u = { a: 2,  b: 2,  c: 1,  d: 2}

u = {a:2, ["b"]:2, d:2, ...u}; // u = { a: 1,  b: 1,  c: 1,  d: 2}

let state = {
    account: null
  };

state.account="top"; //état non protégé
console.log(state)

// on protège l'état
  function updateState(property, newData) {
    state = Object.freeze({
      ...state,
      [property]: newData
    });
  }

  updateState("account",2);
  console.log(state)
  updateState("account",3);
  console.log(state)
 

  state.account="top"; // pluus possible

  console.log(state) 


L'affichage montre qu'une fois protégé on ne peut pas modifier l'état.

{ account: 'top' }

{ account: 2 }

{ account: 3 }

{ account: 3 }

Object.entries

 const obj = { "un": 1, deux: 2, trois: 3 };


const tab = Object.entries(obj);

console.log(tab) // 

  1. (3) [Array(2), Array(2), Array(2)]
    1. length3


const obj2 = Object.fromEntries(

  Object.entries(obj)

  .map(([ key, val ]) => [ `${key}*2`, val * 2 ])

);

console.log(obj2);

  1. {un*2: 2, deux*2: 4, trois*2: 6}
    1. deux*24
    2. trois*26
    3. un*22

https://codepen.io/dupontcodepen/pen/abEaYeQ

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 !


nvm for windows

 https://github.com/coreybutler/nvm-windows