INSTEAD OF USING FOR LOOPS :

//Avoid
consttotal = 0;
const withTax = [];
const highValue = [];
for ( let i = 0; i < orders.lenght; i++ ) {
	total += orders[i];
	withTax.push(orders[i] * 1.1)
	if (orders[i] > 100) {
		highValue.push(orders[i])	
	}
}

//Do
const total = orders.reduce((acc, cur) => acc + cur )
const withTax = orders.map(value => value * 1.1)
const highValue = orders.filter(value => value > 100 )

OPERATEUR TERNAIRE :

const age = 18; 
age > 18 ? "tu es majeur" : " tu n'es pas majeur"; 

const age = 30;
age > 50 
	? age > 70 
	? "Tu as plus de 70 ans" 
	: " tu as entre 30et 69 ans"
	: "tu as moins de 30ans";

CONVERT NUMBER TO STRING :

const = 18 + "";

FILL ARRAYS :

const users = Array(5).fill(" ");    ====> ['', '', '', '', '']
const users = Array(5).fill(5);		   ====> [5, 5, 5, 5, 5]

FILTER UNIQUE VALUES FROM ARRAY :

const unique = Array.from(new Set)  ===> //get only unique values from the array
const unique = [... new Set(users)]      //even easier

let nombres = [10, 45, 74, 10, 45, 24, 10];
let monSet = new Set(nombres);
console.log(monSet); ===> {10, 45, 74, 24}

DYNAMIC VALUES IN OBJECT :

const dynamic = "hobbies";

const user = {
	name : "cyril",
	email : "[email protected]",
	[dynamic] : "code"
}

SLICING ARRAYS :

const users = [1, 2, 3, 4, 5, 6];
users.length = 3         ===> [1, 2, 3]

users.splice(-3)         ===> [5, 6, 7]
users.splice(-1)         ===> [7]

GENERATE RANDOM NUMBER WITH MAX :

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}
getRandomInt(23);

//GENERATE BETWEEN TWO VALUES : 
function getRandomIntBetweenTwo(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}

SELECT ONE ELEMENT FROM ARRAY, KEEP OTHERS :

const devises = ["Bitcoin", "Euro", "dollars", "Yen"];
const [best, ...shittyOnes] = devises;

console.log(best);        // Bitcoin
console.log(shittyOnes);  // ["Euro", "dollars", "Yen"]

OBJECT TO ARRAY :

const users = {
	name : "cyril",
	email : "[email protected]",
	hobbies : "code"
}
const userArray = Object.keys(users)          ===> ["name", "email", "hobbies"]
const userArray = Object.values(users)        ===> ["cyril", "[email protected]", "code"]

PERFORMANCE :

let startAt = performance.now()

//HERE YOU EXECUTE THE CODE 

let endAt = performance.now()

console.log(`${endAt - startAt}`)
console.time();
for (var i = 0; i < 100000; i++) {
  let square = i ** 2;
}
console.timeEnd();
===> default : 6.696534ms

SHUFFLE ARRAY

const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5);
// Testing
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(shuffleArray(arr));

COPY TO CLIPBOARD

const copyToClipboard = (text) =>
  navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
// Testing
copyToClipboard("Hello World!");

DELETE DARK MODE

const isDarkMode = () =>
  window.matchMedia &&
  window.matchMedia("(prefers-color-scheme: dark)").matches;
// Testing
console.log(isDarkMode());

SCROLL TO TOP

const scrollToTop = (element) =>
  element.scrollIntoView({ behavior: "smooth", block: "start" });

SCROLL TO BOTTOM

const scrollToBottom = (element) =>
  element.scrollIntoView({ behavior: "smooth", block: "end" });

GENERATE RANDOM COLORS

const generateRandomHexColor = () =>
  `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;

USE SPREAD INSTEAD OF PUSH :

let Pokemon = ['pikachu', 'arbok', 'raichu']

//Avoid
Pokemon.push('bulbisaur')
Pokemon.push('salameche')
Pokemon.push('dracaufeu')

//Do
//push
Pokemon = [...Pokemon, 'bulbisaur', 'salameche', 'dracaufeu']
//unshift
Pokemon = ['bulbisaur', 'salameche', 'dracaufeu', ...Pokemon]

Pokemon = ['bulbisaur', 'salameche', ...Pokemon, 'dracaufeu']

DECOMPOSE A STRING INTO AN ARRAY USING SPREAD :

const phrase = "Bonjour, je m'appelle Cyril";
const phraseArray = [...phrase];
//(27) ["B", "o", "n", "j", "o", "u", "r", ",", etc ... ]

Palyndrome ?

split(" ").reverse().join(" ")

Fonctions Callback :

Modifier la fonction operation pour qu’elle puisse accepter deux fonctions callback ensuite retourner le resultat de la composition des deux. Par exemple :

operation (2, 3 , 6, somme, produit) retourne 30 = (2+ 3) * 6
function somme (a, b) {
    return a + b;
}

function produit (resultat, multiplier) {
    return resultat * multiplier;
}

function operation (a, b, c, fonction1, fonction2) {
    return fonction2(fonction1(a, b), c);
}

console.log(operation(2, 3, 6, somme, produit));

JSON to STRING/ STRING to JSON

OBJECT to STRING : 
JSON.stringify(ObjectToStringify);

STRING to OBJECT 
JSON.parse(StringToObject);

CONVERT BINARY TO STRING

function binaryAgent(str) {
  return str.split(' ') //Split string in array of binary chars
   .map(bin => String.fromCharCode(parseInt(bin, 2))) //Map every binary char to real char
   .join(''); //Join the array back to a string

}

console.log(binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 
01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111"));
===> "Aren't bonfires fun!?" 

INFOS ABOUT CONSOLE.LOG :

https://developers.google.com/web/tools/chrome-devtools/console/api

const foo = {name : "cyril", age : 22}
const boo = {name : "cyril", age : 22}
const soo = {name : "cyril", age : 22}

//Avoid
console.log(foo) 
console.log(boo)
console.log(soo)

//Do 
console.log({foo, boo, soo})

Creer un tableau dans la console :

console.table([foo, boo, soo])

DO / DONT with ASYNC / AWAIT

https://dev.to/imichaelowolabi/this-is-why-your-nodejs-application-is-slow-206j

definition des data + promesses pour les recuperer

const employee = [
  { id: 1, firstName: 'Ayo', lastName: 'Tunmise', dob: '1980-07-28' },
  { id: 2, firstName: 'Dayo', lastName: 'Owolabi', dob: '2000-03-08' },
  { id: 3, firstName: 'Michael', lastName: 'Ikechukwu', dob: '1997-01-31' },
  { id: 4, firstName: 'Hammed', lastName: 'Tukur', dob: '1900-08-07' },
  { id: 5, firstName: 'Bukola', lastName: 'Agbabiaka', dob: '2001-12-09' },
];

// Function to get employee records from the DB
const getAllEmployees = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(employee)
    }, 1000);
  })
};

// Employee next of kin records in the DB
const nextOfKin = [
  { id: 2, employeeId: 2, fullName: 'Ikoyi Obalende', email: '[email protected]' },
  { id: 3, employeeId: 3, fullName: 'Allen Ikeja', email: '[email protected]' },
  { id: 4, employeeId: 4, fullName: 'Oluyole Ife', email: '[email protected]' },
  { id: 5, employeeId: 5, fullName: 'Chinagoromu Ahmed', email: '[email protected]' },
  { id: 1, employeeId: 1, fullName: 'Mokola Ibadan', email: '[email protected]' },
]

// Function to get individual employee next of kin data from the DB
const getEmployeeNextOfKin = (employeeId) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(nextOfKin.find(nextOfKin => nextOfKin.employeeId === employeeId));
    }, 1000);
  });
};

DONT : (takes for ex 6s to execute !! )

// Application logic that get employee records alongside their individual next of kin data
const getAllEmployeeInformation = async () => {
  // Start recording the execution time of the following code.
  console.time('bad await')
  const allEmployees = await getAllEmployees(); // Get all employee from the DB

  const allEmployeeRecords = [];

  // Map individual employee record with their next of kin data and return the mapped data
  for (const employee of allEmployees) {
    const nextOfKin = await getEmployeeNextOfKin(employee.id);
    allEmployeeRecords.push({ ...employee, nextOfKin });
  }
  console.log(allEmployeeRecords);

  // Stop recording the execution time and log the elapsed time to the console.
  console.timeEnd('bad await');
  return allEmployeeRecords;
}

getAllEmployeeInformation();

DO :

const getAllEmployeeInformation = async () => {
  // Start recording the execution time of the following code.
  console.time('better await')
  const allEmployees = await getAllEmployees(); // Get all employee from the DB

  // Map individual employee record with their next of kin data and return the mapped data
  const employeeNextOfKinPromise = allEmployees.map(employee => {
    return getEmployeeNextOfKin(employee.id).then(nextOfKin => {
      return { ...employee, nextOfKin };
    });
  })

  // Execute all the accumulated promises in parallel so that they don't block eack other and improve the response time
  const allEmployeeRecords = await Promise.all(employeeNextOfKinPromise);
  console.log(allEmployeeRecords);

  // Stop recording the execution time and log the elapsed time to the console.
  console.timeEnd('better await')
  return allEmployeeRecords;
}

getAllEmployeeInformation();