Javascript Memo

◾️ ES6 / ECMAScript 2015 / ES2015 spec

◾️ BABEL

2015年度ES6以前ES5などのjavascript transcompileはBABELがやってくれるから最新で書くことが可能

◾️ html javascirpt import : use defer for downloading delay

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Momentum</title>
    <link rel="stylesheet" href="index.css" />
    <script defer src="main.js"></script>
</head>

◾️ ‘use strict’

'use strict';

// constant
const day = 7;

// variable
let var = 0 ;

// do not use var type 
// use const or let

function test() {
    let count = 0;
    console.log(`count is ${count} type is ${typeof count}`);

    const infinity = 1 / 0;
    const negativeInfinity = -1 / 0;
    const nan = "abc" / 4;

    // `` 
    const hello = "hello";
    console.log(`${hello} world`);
    console.log(hello + " world");

    // false : 0 / null / undefined / Nan / ''
    // true : any other value
    console.log(0 == flase); // true
    console.log(0 === flase); // false
    console.log('' == flase); // false
    console.log('' == flase); // false
    console.log(null == undefined); //true

    // symbol : create unique identifiers for objects
    const symbol1 = Symbol("test");
    const symbol2 = Symbol("test");
    // symbol1 !== symbol2 false

    const sym1 = Symbol.for("test");
    const sym2 = Symbol.for("test");
    // sym1 === sym2 true
}

// es6 from default value
function showMsg(msg, from = "james") {
    console.log(`${msg} ${from}`);
}
showMsg("Hi")

function doAll(...args) {
    for (const arg of args) {
        console.log(arg)
    }
    // args.forEach( (arg) => console.log(arg));

    // return undefined;
}

doAll("java", "python", "react");

// first-class function : can assign var / pass param / return val

// arrow function
const sum = (a,b) => a+b;

//IIFE : immediately Invoked Function Expression
(function hello() {
    console.log("test");
})();
// class from ES6
class Car {
    constructor(brand) {
        this.brand = brand;
    }

    run() {
       console.log(`${this.brand} run and run`); 
    }
}

const honda = new Car("honda");
honda.run();
class User {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    get age() {
        return this._age;
    }

    set age(value) {
        this._age = value < 0 ?  0 : value
    }
}

const brian = new User("brian", 22);
class Animal {

  constructor(name) {
    this.speed = 0;
    this.name = name;
  }

  run() {
    console.log("run");
  }
}

// class extends
class Rabbit extends Animal {
  hide() {
    console.log("hide");
  }

  // overloading
  run() {
    console.log("run fast");
  }
}

let rabbit = new Rabbit("RED");
rabbit.run();
const obj1 = {}; // object literal
const obj2 = new Object(); // object constructor

const user = {name: "james", age: 23};
// dot property
console.log(user.name);
// computed property
console.log(user["name"]);

// computed property ex
function printValue(obj, key) {
    console.log(obj[key]:
}
printValue(user, "name");

// property and value
const user1 = { name:"james", age:23};
const user2 = new User("Mike", age:42);

// constructor function
function User(name, age) {
    // this = {}:
    this.name = name;
    this.age = age;
    // return this;
}

// object copy
const user3 = {};
Object.assign(user3, user1);
// const user3 = Object.assign({}, user1);
const user4 = {name:"test", age:22, power:"up"};
const user5 = Object.assign({}, user3, user4);
console.log(user5.name);
console.log(user5.age);
console.log(user5.power);


// property check : key in obj
console.log("name" in User);

for (key in User) {
    console.log(key);
}

const array = [1,2,3,4];
for( val of array ) {
    console.log(val);
}

// push()/pop()/forEach()/delete:array.splice(1,1)/delete and insert:array.splice(1,0,5,6)/concat/indexof()/includes()
  // Q1. make a string out of an array
  {
    const fruits = ['apple', 'banana', 'orange'];
    const joinFruits = fruits.join(" ");
    console.log(joinFruits);
  }
  
  // Q2. make an array out of a string
  {
    const fruits = "apple,banana,orange";
    const splitFruits = fruits.split(",")
    console.log(splitFruits);

  }
  
  // Q3. make this array look like this: [5, 4, 3, 2, 1]
  {
    const array = [1, 2, 3, 4, 5];
    console.log(array.reverse());
  }
  
  // Q4. make new array without the first two elements
  {
    const array = [1, 2, 3, 4, 5];
    const filtered = array.filter( (item) => item > 2);
    console.log(filtered);
    console.log(array);
  }
  
  class Student {
    constructor(name, age, enrolled, score) {
      this.name = name;
      this.age = age;
      this.enrolled = enrolled;
      this.score = score;
    }
  }
  const students = [
    new Student('A', 29, true, 45),
    new Student('B', 28, false, 80),
    new Student('C', 30, true, 90),
    new Student('D', 40, false, 66),
    new Student('E', 18, true, 88),
  ];
  
  // Q5. find a student with the score 90
  {
      const filteredStudent = students.filter( (student) => student.score === 90);
      console.log(filteredStudent);

      const filteredStudent1 = students.find( (student) => student.score === 90);
      console.log(filteredStudent1);
  }
  
  // Q6. make an array of enrolled students
  {
      const studentArr = students.filter( student => student.enrolled === true );
      console.log(studentArr);
  }
  
  // Q7. make an array containing only the students' scores
  // result should be: [45, 80, 90, 66, 88]
  {
    const scoreArr = students.map( student => student.score );
    console.log(scoreArr);
  }
  
  // Q8. check if there is a student with the score lower than 50
  {
    const isStudent = students.some( student => student.score < 50 );
    console.log(isStudent);   
  }
  
  // Q9. compute students' total score
  {
    const avgScore = students.map( student => student.score ).reduce( (accumulator, currentValue) => accumulator + currentValue );
    console.log(avgScore);

    // return value is prev param(recursive), iniitial value:0
    const avgScore1 = students.reduce( (prev, cur) => prev + cur.score, 0);
    console.log(avgScore1)
  }
  
  // Q10. make a string containing all the scores
  // result should be: '45, 80, 90, 66, 88'
  {
    const strScoreAll = students.map( student => student.score ).join();
    console.log(strScoreAll);
  }
  
  // Q11. result should be: '45, 66, 80, 88, 90'
  {
    const sortedScore = students.map( student => student.score ).sort((a, b) => a - b);
    console.log(sortedScore);
  }

◾️ AJAX

XMLHttpRequest

fetch() API : not support IE

JSON

const car =  {
    name : "honda",
    color : "red",
    size : null,
    made : new Date(),
    run : () => {
        console.log(`${name} run`);
    }
};

console.log(car);

// not include run method 
const jsonStr = JSON.stringify(car);
console.log(jsonStr);

// selected property serialize
const jsonStr1 = JSON.stringify(car, ["name", "made"]);
console.log(jsonStr1);

// callback
const jsonStr2 = JSON.stringify(car, (k, v) => {
    console.log(`key : ${k}, value : ${v}`);
    return k === "name" ? "toyota" : v;
});
console.log(jsonStr2);

console.log("---------------------");

const obj = JSON.parse(jsonStr);
console.log(obj);
//obj.run(); not exist

const obj1 = JSON.stringify(jsonStr, (k, v) => {
    console.log(`key : ${k}, value : ${v}`);
    return k === "made" ? new Date(v) : v;
});
console.log(obj1);

◾️ callback hell(worst example)

class UserStorage {
    loginUser(id, pwd, onSuccess, onFailure) {
        setTimeout( () => {
            if(id === "admin" && pwd ==="admin") {
                onSuccess(id);
            } else {
                onFailure(new Error("not found"));
            }
        })
    }

    getRoles(user, onSuccess, onFailure) {
        setTimeout( () => {
            if(user === "admin") {
                onSuccess({name:"admin", role:"admin"});
            } else {
                onFailure(new Error("no access"));
            }
        }, 0)
    }
}


function processLogin() {
    const userStorage = new UserStorage();
    const id = prompt("enter your id");
    let pwd = "";
    
    // false : 0 / null / undefined / Nan / ''
    if(id != false) {
        pwd = prompt("enter your password");
    }

    console.log(`id is ${id} ${typeof id} and pwd is ${pwd}`);
    userStorage.loginUser(
        id,
        pwd,
        (id) => {
            return userStorage.getRoles(
                id,
                userWithRole => alert(`Hello ${id} with role ${pwd}`),
                error => {console.log(error)}
            )
        },
        error => { console.log("login error")}
    )
}

function init() {
    loginBtn.addEventListener("click", processLogin);
}

init();

◾️ callback -> promise

class UserStorage {
    loginUser(id, pwd) {
        return new Promise((resolve, reject) => {
            setTimeout( () => {
                if(id === "admin" && pwd ==="admin") {
                    resolve(id);
                } else {
                    reject(new Error("not found"));
                }
            }, 0);
        });   
    }

    getRoles(id) {
        return new Promise( (resolve, reject) => {
            setTimeout( () => {
                if(id === "admin") {
                    resolve({name:"admin", role:"admin"});
                } else {
                    reject(new Error("no access"));
                }
            }, 0);
        });
    }
}

function processLogin() {
    const userStorage = new UserStorage();
    const id = prompt("enter your id");
    let pwd = "";
    
    // false : 0 / null / undefined / Nan / ''
    if(id != false) {
        pwd = prompt("enter your password");
    }

    userStorage.loginUser(id, pwd)
    .then(userStorage.getRoles)
    .then(user => alert(`Hello ${user.name} with role ${user.role}`))
    .catch(message => alert(`${message}`));
}

function init() {
    loginBtn.addEventListener("click", processLogin);
}

init();

◾️ promise example

'use strict';

// promise is a javascript object for async operation
// state : pending -> fulfilled or rejected
// producer vs consumer


// producer -> execute immediately
const promise = new Promise((resolve, reject) => {
    // do some heavy work()
    console.log("doing somethong...");
    setTimeout( () => {
        let success = true;

        if(success) {
            resolve("porcess async response");
        }
        else {
            reject(new Error("network error occured"));
        }
    }, 2000);
});

// consumenrs
promise.then( value => {
    console.log(value);
}).catch(
    error=> {
        console.log(error);
    }
).finally(
    () => {
        console.log("finally");
    }
);


//----------------------
// promise chaining
//----------------------
const fetchNum = new Promise((resolve, reject) => {
    setTimeout(() => resolve(1), 1000);
});

fetchNum
.then( num => num + 1)
.then( num => num *2)
.then( num => {
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve(num-1), 1000);
    })
}).then(
    num => {
        console.log(num);
    }
);

//----------------------
// error handling
//----------------------
const getWater = () => {
    return new Promise((resolve, reject) => {
        console.log("get water........");
        setTimeout(() => resolve("water"), 1000);
    })
}

const freeze = (water) => {
    return new Promise((resolve, reject) => {
        console.log("freeze water........");
        setTimeout(() => resolve(`${water} >> ice`), 1000);
    })
} 

const cook = (ice) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve(`${ice} >> icecream`), 1000);
    })
}

console.log("--------");
// getWater()
// .then(water => freeze(water))
// .then(ice => cook(ice))
// .then(icecream => console.log(icecream));

// skip one param 
getWater() //
.then(freeze)
.catch(error => {
    return "supermarket water"
})
.then(cook)
.then(console.log)
.catch(console.log);

◾️ async : return promise

//syntactic sugar
// async & await
// clear style of using promise

// async : return new Promise()
async function fetchUser() {
    return "genie";
}

// same logic of promise
function fetchUser() {
    return new Promise( (resolve, reject) => {
        resolve("genie");
    })
}

◾️ async / await

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function getWater() {
    await delay(1000);
    return "water";
}

async function getCoffee() {
    await delay(1000);
    return "coffee";
}

// it takes 2sec
async function makeCoffee1() {
    const water = await getWater();
    const coffee = await getCoffee();
    return `${water} and ${coffee} is mixed`;
}

// it takes 1sec
async function makeCoffee2() {
    const waterPromise = getWater();
    const coffeePromise = getCoffee();

    const water = await waterPromise;
    const coffee = await coffeePromise;
    return `${water} and ${coffee} is mixed`;
}

makeCoffee1().then(console.log);
makeCoffee2().then(console.log);

◾️ useful api : Promise.all() or Promise.race()

◾️ set object key with variable in ES6

var key = "name";
var person = {[key]:"JAMES"};
console.log(person); //{ name="JAMES"}

◾️ spread / rest operator

const numbers = [1,2];
const newNumbers = [...numbers, 3];

const person = { age:18, name:"john };
const copyPerson = {...persion};

const filter = (...args) =>  { return args.filter(item => item > 1);}
filter(1,2,3);

◾️ localStorage object get/set

localStorage.setItem("KEY", JSON.stringify(obj));
let parsedObj = JSON.parse(localStorage.getItem("KEY"))

◾️ random string

Math.random().toString(36).substring(2)
"ayq79qnwfs5"
Math.random().toString(36).substring(2)
"vvr5pdak8mo"

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です