Hello JS World

 

Вторая лекция

План

 

  • Архитектура JavaScript
  • Алгоритмы и паттерны
  • NPM и популярные пакеты
  • Практические задачи

 

0

Азы JavaScript

 

1

Типы

 

typeof 123 // "number"

typeof true // "boolean"

typeof "foo" // "string"

typeof {id:12, name: "John"} // "object"

typeof [1, 4, 9] // "object"

typeof null // "object"  (1)

typeof undefined // "undefined"

typeof function(){ return 1+1; } // "function"  (2)

P.S.  Lodash; _.isArray(ar)

1

RegExp

 

var re = /ab*c/ig;
var re = new RegExp('ab*c', 'ig');

// ac
// Abc
// aBBBBBBBc

var str = "HelloaBBBBBBBcWorld Hacker";
str.replace(re, ' JS ');
// Hello JS World H JS ker

1

Date

 

var date = new Date();
// Wed Feb 17 2016 16:01:50 GMT+0400 (SAMT)

var str = "Wed Feb 17 2016 16:01:50 GMT+0400 (SAMT)"
var date = new Date(str);

var str = date.toISOString();
// 2016-02-17T12:01:50.000Z

var timestamp = date.getTime();  1455710510000
timestamp = 1*date;
timestamp = +date;

P.S.  Moment.js

1

JSON

 

var user = {
    firstName: "John",
    lastName: "Connor",
    age: 8 * 2
};

var json = JSON.stringify(user);
// {firstName:"John",lastName: "Connor",age:16}


/**
 * Как-то отправляем в браузер, и как-то принимаем
 */

var user = JSON.parse(json);
if(user.age < 18){
    alert("Вход запрещен");
}

1

Архитектура JS

2

Event Loop

2

Скорость?

2

Выгода?

2

Garbage

2

Асинхронность

3

Сравним

// Синхронно

var rounded = Math.round(1.5);
// do something else


/////////


// Асинхронно
var data = null;
getData({userId:123}, function(raw){
    data = Math.round(raw);
    // do something else
})

// чтото паралельное

3

Как принято?

function getData(server, userId, /*...*/ next){
    // do something
}

//////////

getData("https://vk.com", 1, 
    function(err, user, html /*...*/){
    

})

3

Что делать нельзя?

while(new Date().getTime() < now + 1000) {  
    // ничего не делаем
}

console.log("Прошла одна секунда, друг")

/// Запрос к базе
/// Запрос на диск
/// Запрос в гугл
  • Всегда 1 процесс 1 поток (v8)
  • Не существует функции sleep()


3

Как быть?

setTimeout(function(){

    console.log("Прошла одна секунда, друг")
    
    /// Запрос к базе
    /// Запрос на диск
    /// Запрос в гугл
}, 1000);

3

Problems?

setTimeout(function(){
    console.log("Прошла одна секунда, друг")
    
    requestToDB({ userId:101001 }, function(err, user){
        if (err) {
           return showError(err);
        } else {         
           findInFile("apple.json", function(err, userJson){
              if(err){
                return showError(err);
              }
            
              findInGoogle("Steve Jobs", function(err, data){
                if(err){
                  return showError(err);
                }
                showSuccess(user,userJson,data)
              });
           });
        }
    });
}, 1000);

3

Сallback hell

 

Pyramid of Doom

3

Promises

function isUserTooYoung(id, callback) {
    openDatabase(function(err, db) {
        if (err) showError(err);
        getCollection(db, 'users', function(err, col) {
            if (err) showError(err);
            find(col, {'id': id},function(err, result) {
                if (err) showError(err);
                result.filter(function(err, user) {
                    if (err) showError(err);
                    callback(user.age < cutoffAge)
                })
            })
        })
    })
}

function isUserTooYoung(id) {
    return openDatabase(db)
        .then(getCollection)
        .then(find.bind(null, {'id': id}))
        .then(function(user) {
            return user.age < cutoffAge;
        })
        .catch(showError)
}

3

Async-Await

function isUserTooYoung(id) {
    return openDatabase(db)
        .then(getCollection)
        .then(find.bind(null, {'id': id}))
        .then(function(user) {
            return user.age < cutoffAge;
        })
        .carch(showError)
}

async function isUserTooYoung(id) {
    try {
        const a = await openDatabase(db)
        const b = await getCollection(a)
        const user = await find(b, {'id': id})
        return user.age < cutoffAge;
    } catch (err) {
        showError(err)
    }
}

3

Наследование

4

Наследование

  • Функциональное наследование
  • Прототипное наследование
  • Композиция через _.extend
  • ES6 Классы

4

Прототипы

4

ES6 Классы

 


class ColorPoint extends Point {
  static getSquare(point1, point2) {
    return Math.abs(point1.x - point2.x) * 
      Math.abs(point1.y - point2.y);
  }
  constructor(x, y, color) {
    super(x, y); 
    this.color = color;
  }
  toObject() {
    return {
      ...super.toObject(),
      color: this.color,
    };
  }
}

const point1 = new Colorpoint(30, 40, 'red')
const point2 = new Colorpoint(10, 20, 'red')
console.log(ColorPoint.getSquare(point1, point2))

4

ECMAScript

5

5

5

Arrows

// Expression bodies
var odds = evens.map(v => v + 1);
var nums = evens.map((v, i) => v + i);
var pairs = evens.map(v => ({even: v, odd: v + 1}));

// Statement bodies
nums.forEach(v => {
  if (v % 5 === 0)
    fives.push(v);
});

// Lexical this
var bob = {
  _name: "Bob",
  _friends: [],
  printFriends() {
    this._friends.forEach(f =>
      console.log(this._name + " knows " + f));
  }
}

5

Templates

// Basic literal string creation
`In JavaScript '\n' is a line-feed.`

// Multiline strings
`In JavaScript this is
 not legal.`

// String interpolation
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

// Construct an HTTP request prefix is used to interpret the replacements and construction
POST`http://foo.org/bar?a=${a}&b=${b}
     Content-Type: application/json
     X-Credentials: ${credentials}
     { "foo": ${foo},
       "bar": ${bar}}`(myOnReadyStateChangeHandler);

5

Let, Const

function f() {
  {
    let x;
    {
      // okay, block scoped name
      const x = "sneaky";
      // error, const
      x = "foo";
    }
    // error, already declared in block
    let x = "inner";
  }
}

5

Default, Rest, Spread

function f(x, y=12) {
  // y is 12 if not passed (or passed as undefined)
  return x + y;
}
f(3) == 15
function f(x, ...y) {
  // y is an Array
  return x * y.length;
}
f(3, "hello", true) == 6
function f(x, y, z) {
  return x + y + z;
}
// Pass each elem of array as argument
f(...[1,2,3]) == 6

5

ES6 features

Babel

6

6

CLI


npm i babel-cli -g

babel-node index.js

babel-node tools/run start  
   | node ./src/utils/bunyan -o short -l trace

node start.js


{
  "scripts": {
     "babel-build": "rimraf lib && 
        babel src --out-dir lib --source-maps inline --copy-files && 
        cp {package.json,README.md} lib/"
   }
}

6

Presets & Plugins

.babelrc
{
  "presets": [
    "es2015",
    "react",
    "node5",
    "stage-0"
  ],
  "plugins": [
    "jsx-control-statements",
    "react-require",
    "transform-decorators-legacy"
  ]
}

{
  "dependencies": {
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-node5": "^11.1.0",
    "babel-preset-react": "^6.5.0",
    "babel-preset-stage-0": "^6.5.0",
  }
}

6

Stages

6

NPM

7

Packages.json

npm init
npm install
npm install --save lodash express svg2png
npm start
npm run dev
{
  "name": "svg",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon index.js",
    "start": "node index.js",
    "prod": "npm install && node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "isuvorov",
  "license": "ISC",
  "dependencies": {
    "lodash": "^3.10.1",
    "express": "^4.13.4",
    "svg2png": "^3.0.0"
  }
}
npm i -S express
npm i -g nodemon
npm i -D bunyan

7

Фреймворки

7

Полезные пакеты

7

Express

  • express
  • express-async-router
  • express-graphql
  • express-jwt
  • express-ws
  • express-xml-bodyparser
  • express-winston

7

PUSH-notification

  • node-gcm - A NodeJS wrapper library port to send data to Android devices via Google Cloud Messaging
  • node-apn - Apple Push Notification module for Node.js
  • fcm-push - Firebase Cloud Message push notification

7

Что почитать?

А также, очень много ссылок на nodejs библиотеки и туториалы

8

Ложка дегтя

8

статьте лайки, подписывайтесь на канал

Спасибо за внимание

Игорь Суворов

telegram.me/isuvorov

vk.com/igor.suvorov

github.com/isuvorov

 

Вопросы?

NaN

Hello JS World

By Igor Suvorov

Hello JS World

"summary" : "#!md * Основные архитектурные особенности JavaScript. * Новым конструкциям ES6, ES7. * JavaScript на сервере - Node.js. * Пакетный менеджер NPM. * Инструментом Babel. * Паттерны асинхронного программирования (Promises, Async-await).

  • 2,214