Vue d'ensemble de
JavaScript post-ES6
CC-BY-NC-4.0 / Jan. 2021 / Loïc TRUCHOT
// LET && CONST
// let, const
const q = "Carbon dioxide formula?";
if (typeof q === "string") {
var a1 = "O2"; // let a, const a
a1 = "CO2";
}
console.log(a1);
let toto = "yo";
{
const a2 = "H2O";
let a3 = "Au";
a3 = "Bo";
console.log(a2, a3, toto);
toto = 5;
}
console.log(toto);
const qsts = ["1+1", "2+2"];
qsts.push(6);
// qsts = [];
// console.log(a2, a3);
for (let i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, i * 1000);
}
let it be
const game = 'Mario"MO"';
const players = "Peach"
+ ", 'Toad', Mario";
const templateString = `
<div>
<p>"Hello ${players}. Welcome on ${game}."</p>
</div>
`;
Templated strings
function end (player) {
return "Game over..." + player;
}
const end1 = function (player) {
return "Game over..." + player;
}
const end2 = (player) => {
return "Game over..." + player;
}
const end3 = player => {
return "Game over..." + player;
}
const end4 = player => "Game over..." + player;
console.log(end4("Commander Shepard"));
export const balance = 10;
export const double = n => n * 2;
import { balance, double } from "./file1";
console.log(double(balance));
file1.js
file2.js
import $ from 'jquery';
import { head, tail } from 'ramda';
$('body').html('coucou');
console.log(head([1, 2]));
Première SPA moderne
Bonus2 : Une des vues est un formulaire dont le contenu est envoyé avec AJAX à un site distant fictif (la requête est tentée)
Bonus1 : Le lien présentement selectionné est mis en avant
Destucturing
const arr = [1, 2, 3];
const [a, b, c] = arr;
console.log(a, b, c);
const quizzSpecial = {
name: "La cité de la peur",
editor: "Pay2Win",
price: 20,
type: "Quizz"
};
const { name, editor } = quizzSpecial;
console.log(name, editor);
const checkPrice = ({ price }) => {
console.log(price);
};
checkPrice(quizzSpecial);
Math.max(5, 6, 8, 9, 11, 999); // ?
const display3winners = (a, b, c) => {
console.log(a, b, c);
};
const arr = [
"Peach",
"Sonic",
"Momo54"
];
display3winners(...arr);
const arr2 = [
"Chiffon1050",
"Jean louis",
...arr
];
display3winners(...arr2);
function add(...nbs) {
let total = 0;
for (const nb of nbs) {
total += nb;
}
return total;
}
console.log(add(1, 2, 3, 4));
export const spread = () => {
const o1 = { toto: "titi" };
const o2 = {...o1};
const o3 = {
tutu: "tete",
...o2
};
console.log(o1, o2, o3);
const a1 = [1, 2, 3];
const a2 = [...a1];
console.log(a1, a2);
// clone deep
const o4 = JSON.parse(
JSON.stringify(o3)
);
console.log(o4);
}
Destucturing
& Rest
const [a, b, ...c] = arr2;
console.log(a, b, c);
const quizzSpecial = {
name: "La cité de la peur",
editor: "Pay2Win",
price: 20,
type: "Quizz"
};
const { name, editor } = quizzSpecial;
console.log(name, editor);
const checkPrice = ({ price }) => {
console.log(price);
};
checkPrice(quizzSpecial);
Clés calculées Clés raccourcies
// SHORT HAND KEY-VALUE
// COMPUTED KEYS
const key = "notice3";
const prix = 21;
const notice3 = {};
const divineLumiere = {
livre: "La divine lumière",
auteur: "Eiji Yoshikawa",
prix,
type: "roman",
[key]: notice3
};
console.log(divineLumiere);
Safe navigation
& Coalescence
// classes
export class Game {
constructor(gameName, nbPlayers) {
this.nbPlayers = nbPlayers;
this.gameName = gameName;
this.editor = 'Pay2Win Corp.';
}
// shorthand method
launch() {
console.log(`${this.editor} game
named ${this.gameName} will begin !`);
// arrow function needed
setTimeout(function() {
console.log(this.nbPlayers +
' players participate');
}, 3000);
}
}
export class Quizz extends Game {
constructor(gameName, nbPlayers) {
super(gameName, nbPlayers);
this.type = 'Quizz';
}
launch() {
super.launch();
console.log(this.gameName + ' is a '
+ this.type);
}
}
...Orienté Objet !
On peut donner aux instances un nom et une couleur
Les instances reçoivent aussi un "top" et un "left" tirés au hasard entre 0 et 1000px
↓ Alternative... ↓
O O Games
Avada kedavra
A la fin, Voldemort et Harry meurent, Hermione survit avec 4 pdv
Bonus: Harry ne peut pas mourir car il est immunisé à Avada Kedavra
Bonus 2: ce combat épique se passe dans des setTimeouts
old fashioned functions: function () {}
VS Arrow functions: =>
La récursion, niveau expert
images ? vidéo ? vétérinaire ?
nourriture ? medecine ? aviation ? fleurs ?
Anthropologie et analyse des métiers
un petit mot a propos de
JQuery autorisé et encouragé
puis...
const end = new Promise((resolve, reject) => {
console.log('Game over...');
setTimeout(() => {
resolve('... try again ?');
}, 1000);
});
end.then((val) => console.log(val));
var promise1 = new Promise(function(resolve, reject) {
throw new Error("Oh mon dieu, il y a eu un bug !");
});
promise1.catch(function(error) {
console.error(error);
});
import { get } from "axios";
function pileOuFace() {
return new Promise((resolve, reject) => {
if (Math.random() > 0.5) {
resolve("Réussite");
} else {
reject("Échec");
}
})
}
pileOuFace()
.then(() => get("https://toto.com/api/cadeau"))
.then((cadeau) => mail(cadeau))
.catch(msg => console.log(msg));
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
xhr.onload = () => console.log(xhr.responseText);
xhr.onerror = () => console.error(xhr.statusText);
xhr.send();
fetch('https://api.github.com/users/ltruchot')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => console.error(error))
async function welcomePlayer(playerName) {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log(`La partie commence, ${playerName} !`);
const data = await fetch("https://jsonplaceholder.typicode.com/posts")
.then(res => res.json());
return data;
}
welcomePlayer("Peach");
const data = welcomePlayer("Mario").then(console.log);
Quart d'heure TV chill
import { get } from 'axios';
Promise.all([
get('http://localhost:3000/articles'),
get('http://localhost:3000/users'),
]).then((arr) => {
console.log(arr[0].data)
console.log(arr[1].data);
});
Et ses fichiers JSON
Le constructeur Set
const lastPlayers = new Set([
"Toad",
"Wario"
]);
lastPlayers.add("Wario");
console.log(lastPlayers);
lastPlayers.delete("Toad");
console.log(lastPlayers);
Set
Le constructeur Map
const lastPlayer = new Map([
["name", "Luigi"]
]);
console.log(lastPlayer);
lastPlayer.set("age", 45);
console.log(lastPlayer);
lastPlayer.forEach(a =>
console.log(a));
console.log(
lastPlayer.has("age"),
lastPlayer.has("test"),
lastPlayer.get("name")
);
const users = [
{
prenom: 'Étienne',
age: 42,
sexe: 'M',
hobbies: ['videogames', 'cooking'],
}
];
Pourquoi reduce est la plus importantes des méthodes de JavaScript ?
Exemples
// la somme
[1,2,3].reduce((a, b) => a + b); // 6
[].reduce((a, b) => a + b); // ???
[].reduce((a, b) => a + b, 0); // 0
// la multiplication
[1,2,3].reduce((a, b) => a * b); // 6
[1,2,3].reduce((a, b) => a * b, 0); // ???
[].reduce((a, b) => a * b, 1); //
import { map, reduce, pipe, prop } from 'ramda';
const double = a => a * 2;
const x4 = pipe(double, double);
console.log(x4(100));
const arr = [{ name: 'Samir', age: 24 }, { name: 'Gaël', age: 55 }];
const getAge = map(prop('age')); // pluck
const sum = reduce((a, b) => a + b, 0); // sum
const divide = divider => nb => nb / divider; // divide
const ageAverage = pipe(getAge, sum, divide(arr.length)); // ou converge/lift
console.log(ageAverage(arr));
Comment coder notre propre « pipe » ou « compose »
const vetements = [
{nom: "chemise", taille: "L"},
{nom: "chemise", taille: "XL"},
{nom: "chemise", taille: "XL"},
{nom: "chemise", taille: "S"},
{nom: "jean", taille: "S"},
{nom: "jean", taille: "M"},
];
["L", "XL", "S"]
pipe(map(prop("length")), map(even)) === map(pipe(prop("length")), even))
const animal = {
categorie: 'animal',
son: 'grogne',
dormir() {
console.log('ZZZzzzzzZZZ');
},
parler() {
console.log(this.son);
},
};
animal.parler();
const chat = Object.create(animal, { son: { value: 'miaou' } });
chat.dormir();
chat.parler();
Exercice collectif:
Exercice collectif:
Exercice collectif:
THANK'S EVERYONE
It's finally done ! See you soon