Javascript

09/12/20 danny

Définition

Mots clés

  • ECMA
    European Computer Manufacturers Association
     
  • ES
    E
    CMAScript
    Ensemble de normes pour langages de type script
     
  • ES6 ou ES2015
    ECMAScript Edition 6 Juin 2015
     
  • ES7
    ECMAScript Edition 7 Juin 2016

Const, let, var

Let

  • Portée limitée au bloc courant.

Const

  • Déclare une constante disponible en lecture uniquement.
    Doit être déclarée avec une valeur initiale.
    La portée est celle du bloc.
    Si elle est définie hors de toute fonction la portée est globale

Var

  • Portée limitée à une fonction

Function

Comment utiliser les fonctions

  • Déclaration de Fonctions
    Function Declaration
  • Expression de Fonctions
    Function Expressions
function declaration() {
    console.log('Declaration de function');
}

const expression1 = function example() {
    console.log('Expression1 de function');
}

const expression2 = function () {
    console.log('Expression2 de function');
}

const expression3 = () => {
    console.log('Expression3 de function');
}

declaration();
expression1();
expression2();
expression3();



Division

function testDivision() {
    // division  = 3.33   
    let number1 = 10 / 3;
    // reste = 1
    let number2 = 10 % 3;
    // partie entière = 3
    let number3 = Math.trunc(10 / 3);
    console.log(number1)
    console.log(number2)
    console.log(number3)
}

testDivision();

Opérateurs logiques

nom des opérateur

  • AND
    &&
  • OR
    ||
function test() {
  let x = 11;
  if ((x != 11) && (x != 12)) {
    console.log('different 10');
  }
  if ((x === 11) || (x ===12)) {
    console.log('equal 11 or 12');
  }
}

test();

Boucles & loop

for (i = 0; i < 5; i++) {
 console.log(i);
}

while (i < 10) {
  console.log(i);
  i++;
}

let i = 1;
do {
  i = i + 1;
  console.log(i);
}
while (i < 10);

NaN

Not a Number en anglais
Propriété globale qui réprésente une valeur qui n'est pas un nombre.


function testNan() {
    let valeur1 = 41;
    if (isNaN(valeur1))  {
        console.log('Not a Number:true');
    } else {
        console.log('Not a Number:false');
    }
    let valeur2 = 41 + "text";
    if (isNaN(valeur2))  {
        console.log('Not a Number:true');
    } else {
        console.log('Not a Number:false');
    }
}

testNan();

Types

Javascript dipose de 6 types de donnée

  • Object
  • Number
  • String
  • Boolean
  • Null
  • Undefined

function getAmount(i) {
    let object1 = {
        "name": "Gladiator",
        "budget": 1111,
    }
    console.log(i + ':object1:' + object1);
    console.log(i + ':object1:' + JSON.stringify(object1));

    let string1 = "Gladiator";
    console.log(i + ':string1:' + string1)

    let array1 = [1, 2, 3];
    array1.forEach(res => {
        console.log(i + ':array1:' + res);
    })

    let number1 = 11;
    console.log(i + ':number1:' + number1 / 2)
    console.log(i + ':number1:' + number1 % 2)
    console.log(i + ':number1:' + Math.trunc(number1 / 2))

}

function showAmount() {
    for (let x = 1; x <= 1; ++x) {
        getAmount(x);

    }
}


showAmount();

Number String

function calcul() {

  let string1 = '10';
  let number1 = parseInt(string1) + 20;

  console.log('string1:' + string1);
  console.log('string1:' + number1);

};

calcul();
function stringNumber() {

  let number1 = 4444;
  let string1 = number1.toString();

  console.log('string1:' + string1);
  console.log('string1:' + number1);

};

stringNumber();

Objets

Objet

function showMovie() {
  let object1 =
    [
      { "name": "Gladiator" },
      { "name": "Alien" },
    ];
  console.log('obj:' + object1[2]);
  for (let x = 0; x < 10; ++x) {
    let obj = object1[x];
    if (obj != undefined) {
      console.log('0001:' + JSON.stringify(obj));
    }
  }
}

showMovie();

Date

var dateFormat = require('dateformat');

function showDate() {
  let date = Date.now();
  console.log('0001:' + date);

  var now = new Date();
  let date1 = dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
  console.log('0002:' + date1);
 
  let date2 = dateFormat(now, "dd/mm/yyyy HH:MM:ss");
  console.log('0002:' + date2);
 
}

showDate();

Typeof

function testTypeof() {
    let object1 = [1, 2, 3, 4]
    let null1 = null;
    let string1 = "Gladiator";
    let number1 = 4444;
    let boolean1 = true;
    let undefined1 = undefined;
    console.log('null1:' + typeof object1);
    console.log('null1:' + typeof null1);
    console.log('null1:' + typeof string1);
    console.log('null1:' + typeof number1);
    console.log('null1:' + typeof boolean1);
    console.log('null1:' + typeof undefined1);
}

testTypeof();

Export Modules

// fichier app.js
const lib= require('./lib');

lib.declaration();
lib.expression1();
lib.expression2();
lib.expression3();

// fichier lib.js
function declaration() {
  console.log('Declaration de function');
}

const expression1 = function example() {
  console.log('Expression1 de function');
}

const expression2 = function () {
  console.log('Expression2 de function');
}

const expression3 = () => {
  console.log('Expression3 de function');
}


module.exports = {
  declaration: declaration,
  expression1: expression1,
  expression2: expression2,
  expression3: expression3,
};
// fichier app.js
const lib = require('./lib');

lib.declaration();
lib.expression1();
lib.expression2();
lib.expression3();

// fichier lib.js
function declaration() {
  console.log('Declaration de function');
}

const expression1 = function example() {
  console.log('Expression1 de function');
}

const expression2 = function () {
  console.log('Expression2 de function');
}

const expression3 = () => {
  console.log('Expression3 de function');
}


exports.declaration = declaration;
exports.expression1 = expression1;
exports.expression2 = expression2;
exports.expression3 = expression3;

// fichier lib.js
function sum() {
  console.log('sum');
}

module.exports = sum;

// fichier app.js
const lib = require('./lib');

lib();



Export Import


// Ficher export movie-name.js
function movieName(name) {
  console.log('Movie name :' + name);
}

export { movieName };



// Ficher export movie-director.js
function movieDirector(director) {
  console.log('Movie Director : ' + director)
}

export { movieDirector };


// Fichier import app-modules.js
import { movieName } from './movie-name.js';
import { movieDirector } from './movie-director.js';

function app() {
  movieName('Gladiator');
  movieDirector('Ridley Scott');
}

app();



Les promises ou promesses

function importItem() {
  return new Promise(function (resolve, reject) {
    console.log('0001');
    if (Math.random() > .5) {
      console.log('0002');
      resolve("ok");
    }
    else {
      console.log('0003');
      resolve("not ok");
    }
  });
}

const promise = importItem();
promise
  .then(res => {
    console.log('0004' + res);
  })
  .catch(err => {
    console.log('0005' + err);
  })
  .finally(err => {
    console.log('0006' + err);
  });


Promise then catch

const promise = new Promise((resolve, reject) => {
  if (Math.random() > .3) {
    console.log('resolve');
    resolve(true);
  }
  else {
    if (Math.random() > .5) {
      console.log('reject');
      reject(false);
    }
    else {
      console.log('catch');
      throw 'catch';
    }
  }

});

promise
.then(res => {
  console.log('then:' + res);
})
.catch((error) => {
  console.error('catch:' + error);
});

Solution 1

function importItem() {
  return new Promise(function (resolve, reject) {
    console.log('importItem');
    if (Math.random() > .5) {
      console.log('importItem:true');
      resolve(true);
    }
    else {
      console.log('importItem:false');
      resolve(false);
    }
  });
}

function createItem() {
  return new Promise(function (resolve, reject) {
    console.log('createItem');
    if (Math.random() > .5) {
      console.log('createItem:true');
      resolve(true);
    }
    else {
      console.log('createItem:false');
      resolve(false);
    }
  });
}

function checkItem() {
  return new Promise(function (resolve, reject) {
    console.log('checkItem');
    if (Math.random() > .5) {
      console.log('checkItem:true');
      resolve(true);
    }
    else {
      console.log('checkItem:false');
      resolve(false);
    }
  });
}

importItem()
  .then(res => {
    if (res) {
      console.log('then:importItem' + res);
      checkItem()
        .then(res => {
          if (!res) {
            console.log('then:checkitem:not exist' + res);
            createItem()
              .then(res => {
                console.log('then:createitem' + res);
              })
              .catch(err => {
                console.log('catch:createitem' + err);
              })
          } else {
            console.log('then:checkitem:exist' + res);
          }
        })
        .catch(err => {
          console.log('catch:checkitem' + err);
        })
    }
  })
  .catch(err => {
    console.log('catch:importItem' + err);
  }); 

Chainages

function importItem() {
  return new Promise(function (resolve, reject) {
    console.log('importItem');
    if (Math.random() > .5) {
      console.log('importItem:true');
      resolve(true);
    }
    else {
      console.log('importItem:false');
      resolve(false);
    }
  });
}

function createItem() {
  return new Promise(function (resolve, reject) {
    console.log('createItem');
    if (Math.random() > .5) {
      console.log('createItem:true');
      resolve(true);
    }
    else {
      console.log('createItem:false');
      resolve(false);
    }
  });
}

function checkItem() {
  return new Promise(function (resolve, reject) {
    console.log('checkItem');
    if (Math.random() > .5) {
      console.log('checkItem:true');
      resolve(true);
    }
    else {
      console.log('checkItem:false');
      resolve(false);
    }
  });
}

importItem()
  .then(res => {
    console.log('0001:checkItem:' + res);
    if (res) {
      return !checkItem(res);
    }
  })
  .then(res => {
    console.log('0002:createItem:' + res);
    if (res) {
      return createItem(res);
    }
  })
  .catch(err => {
    console.log('0003:catch:importItem' + err);
  });

Await async

function importItem() {
  return new Promise(function (resolve, reject) {
    console.log('importItem');
    if (Math.random() > .5) {
      console.log('importItem:true');
      resolve(true);
    }
    else {
      console.log('importItem:false');
      resolve(false);
    }
  });
}

function createItem() {
  return new Promise(function (resolve, reject) {
    console.log('createItem');
    if (Math.random() > .5) {
      console.log('createItem:true');
      resolve(true);
    }
    else {
      console.log('createItem:false');
      resolve(false);
    }
  });
}

function checkItem() {
  return new Promise(function (resolve, reject) {
    console.log('checkItem');
    if (Math.random() > .5) {
      console.log('checkItem:true');
      resolve(true);
    }
    else {
      console.log('checkItem:false');
      resolve(false);
    }
  });
}

async function importItems() {
  try {
    const result = await importItem();
    const newResult = await checkItem(result);
    if (!newResult) {
      const finalResult = await createItem(newResult);
      console.log('Résultat final : ' + finalResult);
    }
  } catch (error) {
    console.log('catch:importItem' + err);
  }
}

importItems(); 

Error and await

async function execute() {
  try {
    const databaseNsame = 'mock';
    console.logdddd('0000:' + databaseName);
    return true;
  }
  catch (err) {
    console.log('0001:' + err);
    return false;
  }
}

execute()
  .then(res => {
    console.log('0004:' + res);
    process.exit();
  })
  .catch(err => {
    console.log('0005:' + err);
    process.exit();
  });

Error and promise

function execute() {
  return new Promise(function (resolve, reject) {
    console.log('0001');
    if (Math.random() > .5) {
      console.log('0002');
      resolve("ok");
    }
    else {
      console.log('0003');
      resolve("not ok");
    }
  });
}

execute()
  .then(res => {
    console.log('0004:' + res);
    process.exit();
  })
  .catch(err => {
    console.log('0005:' + err);
    process.exit();
  });

Promise all

function createDomain(param) {
  return new Promise(function (resolve, reject) {
    console.log('createDomain:' + param);
    resolve('createDomain:resolve:' + param);
  });
}

function execute() {
  return new Promise(function (resolve, reject) {
    Promise.all([
      createDomain(1111),
      createDomain(2222),
      createDomain(3333),
      createDomain(4444)
    ])
      .then((res) => {
        console.log('execute:Promise.all:res:' + res)
        resolve(res);
      }).catch((err) => {
        console.log('execute:Promise.all:err:' + err)
        reject('execute:err:' + err);
      });
  });
}

execute()
  .then(res => {
    console.log('execute:res:' + res);
    process.exit();
  })
  .catch(err => {
    console.log('execute:err:' + err);
    process.exit();
  });

Fizz Buzz

function testNumber(number) {
  let div3 = number % 3;
  let div5 = number % 5;
  if (div3 === 0) {
    console.log(number + ':Fizz 3');
  }
  if (div5 === 0) {
    console.log(number + ':Buzz 5');
  }
  if ((div3 === 0) || (div5 === 0)){
    console.log(number + ':Buzz 3 & 5');
  }
  if ((div3 != 0) && (div5 != 0)){
    console.log(number + ':');
  }
}

function testFizzBuzz() {
  for (let x = 1; x <= 10; ++x) {
    testNumber(x);
  }
}

testFizzBuzz();
function getFizz(number) {
  return ((number % 3) === 0)
}

function getBuzz(number) {
  return ((number % 5) === 0)
}

function getFizBuzz(number) {
  let res = false;
  if ((number % 3 === 0) && (number % 5 === 0)) { res = true; }
  return res;
}

function test() {
  let res = false;
  for (let y = 1; y <= 40; ++y) {
    res = false;
    if (getFizz(y)) {
      console.log(y + ':Fizz 3');
      res = true
    }
    if (getBuzz(y)) {
      console.log(y + ':Buzz 5'); res = true
    }
    if (getFizBuzz(y)) {
      console.log(y + ':FizBuzz 3 & 5'); res = true
    }
    if (!res) {
      console.log(y + ':');
    }
  }
}

test();