0%

  • 查询已有queue

    sudo rabbitmqctl list_queues

  • 查询已有exchanges

    sudo rabbitmqctl list_exchanges

Publish/Subscribe

  • Exchanges

    There are a few exchange types available: direct, topic, headers and fanout.

  • Bindings

    A binding is a relationship between an exchange and a queue

http 1.0 http 1.1

  • HTTP1.0最早在网页中使用是1996年,那个时候只是使用一些较为简单的网页和网络的请求,每次请求都需要建立一个单独的连接,上一次和下一次请求完全分离。这种做法,即使每次的请求量都很小,但是客户端和服务端每次建立TCP连接和关闭TCP连接都是相对比较费时的过程,严重影响客户端和服务端的性能。

  • 基于以上的问题,HTTP1.1在1999年广泛应用于现在的各大浏览器网络请求中,同时HTTP1.1也是当前使用最为广泛的HTTP协议(2015年诞生了HTTP2,但是还未大规模应用),这里不详细对比HTTP1.1针对HTTP1.0改进了什么,只是在连接这块,HTTP1.1支持在一个TCP连接上传送多个HTTP请求和响应,减少了建立和关闭连接的消耗延迟,一定程度上弥补了HTTP1.0每次请求都要创建连接的缺点,这就是长连接,HTTP1.1默认使用长连接。

  • 那么,长连接是如何工作的呢?首先,我们要明确一下,长短连接是通信层(TCP)的概念,HTTP是应用层协议,它只能说告诉通信层我打算一段时间内复用TCP通道而没有自己去建立、释放TCP通道的能力。

  • http的keep-alive和tcp的keep-alive的区别
    • http的keep-alive是为了复用已有连接
    • tcp的keep-alive是为了保活,即保证对端还存活,不然对端已经不在了我这边还占着和对端的这个连接,浪费服务器资源,做法是隔一段时间发送一个心跳包到对端服务器,一旦长时间没有接收到应答,就主动关闭连接

WebSockets

WebSockets provide a persistent connection between a client and server that both parties can use to start sending data at any time.**

1
2
// Create a new WebSocket.
var socket = new WebSocket('ws://echo.websocket.org');
  • Once the connection has been established the open event will be fired on your WebSocket instance.

  • 请求

    ws://localhost:9095/webSocket/d72b3660-29a8-4276-9eb1-3373e82fdd92

  • 后台请求的结果传入websocket是通过session建立关联的

SSE(Server-Sent Events)

client

1
2
3
4
GET/POST /api/v1/live-scores 
Accept: text/event-stream
Cache-Control: no-cache
Connection: keep-alive

Accept: text/event-stream indicates the client waiting for event stream from the server, Cache-Control: no-cache indicates that disabling the caching and Connection: keep-alive indicates the persistent connection. This request will give us an open connection which we are going to use to fetch updates. After the connection, the server can send messages when the events are ready to send by the server. The important thing is that events are text messages in UTF-8 encoding.

1
2
3
4
5
6
curl -H "Accept: text/event-stream" -H "Cache-Control: no-cache" -N <SSE_ENDPOINT_URL>
# e.g.
curl -X POST -H "Accept: text/event-stream" -H "Cache-Control: no-cache" -H "User-Key: dongwei" -H "Authorization: Bearer xxxxx" -H "Content-Type: application/json" -d '{"content": "你好"}' -N http://xxx/api

# 对照非流式
curl -X POST -H "Accept: application/json" -H "User-Key: dongwei" -H "Authorization: Bearer xxxxx" -H "Content-Type: application/json" -d '{"content": "你有哪些能力"}' http://xxx/api/

server

Disadvantages

  • One potential downside of using Server-Sent Events is the limitations in data format. Since SSE is restricted to transporting UTF-8 messages, binary data is not supported.
  • When not used over HTTP/2, another limitation is the restricted number of concurrent connections per browser. With only six concurrent open SSE connections allowed at any given time, opening multiple tabs with SSE connections can become a bottleneck. (Credit: Dan Messenger)

ref

BIG DATA: What is, Types, Characteristics & Example

  • Big Data is defined as data that is huge in size. Bigdata is a term used to describe a collection of data that is huge in size and yet growing exponentially with time.
  • Examples of Big Data generation includes stock exchanges, social media sites, jet engines, etc.
  • Big Data could be 1) Structured, 2) Unstructured, 3) Semi-structured
  • Volume, Variety, Velocity, and Variability are few Characteristics of Bigdata
  • Improved customer service, better operational efficiency, Better Decision Making are few advantages of Bigdata

Hadoop EcoSystem and Components

Hadoop Architecture

HDFS Architecture

HDFS cluster primarily consists of a NameNode that manages the file system Metadata and a DataNodes that stores the actual data.

  • Read Operation In HDFS

  • Write Operation In HDFS

MapReduce

The whole process goes through four phases of execution namely, splitting, mapping, shuffling, and reducing.

  1. Jobtracker: Acts like a master (responsible for complete execution of submitted job)
  2. Multiple Task Trackers: Acts like slaves, each of them performing the job

用户

  • 新增用户

    adduser username

    passwd username

    usermod -aG wheel username

    su - username

IP

  • 安装完毕之后,需要设置IP分配

    1. cd /etc/sysconfig/network-scripts/

    2. 再进入编辑ifcfg-e** 文件 执行命令
      vi ifcfg-e**

    3. 修改ONBOOT项

    1
    2
    3
    4
    其中部分内容如下: 
    DEVICE=eth0 #设备名称,可根据ifcofnig命令查看到。
    BOOTPROTO=dhcp #连接方式,dhcp会自动分配地址,此时不需要在下面设置ip和网关
    ONBOOT=yes #yes表示启动就执行该配置,需要改为yes
    1. 修改完后需要重启网络设置,执行

      service network restart

  • 设置静态IP

    • 虚拟机设置

    • 宿主机器设置

      需要设置vmnet8的ip为同一网段的配置

jdk

  • 安装jdk

    sudo yum install java-1.8.0-openjdk-devel

    • find path

    update-alternatives --config java

    • config .bashrc

    export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-1.el7_6.x86_64/jre

mysql

  • 授权所有机器可以从外界访问mysql

    GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'will';

    FLUSH PRIVILEGES;

Skill

  • open tab in new window

    • Press Ctrl + k
    • Release the Ctrl and k keys
    • press O (the letter O, not Zero).
  • save all

    • Press Ctrl + k
    • Release the Ctrl and k keys
    • Press s
  • copy line

    Shift+Alt+Down and Shift+Alt+Up

Plugin

  • fileheader

    ctrl+alt+i can insert comments in the head.

dva = React-Router + Redux + Redux-saga

State

tate 表示 Model 的状态数据

Action

Action 是一个普通 javascript 对象,它是改变 State 的唯一途径。

  • action 必须带有 type 属性指明具体的行为,其它字段可以自定义,如果要发起一个 action 需要使用 dispatch 函数;需要注意的是 dispatch 是在组件 connect Models以后,通过 props 传入的。

dispatch

dispatching function 是一个用于触发 action 的函数

  • action 是改变 State 的唯一途径,但是action只描述了一个行为,而 dipatch 可以看作是触发这个行为的方式,而 Reducer 则是描述如何改变数据的。

  • connect Model 的组件通过 props 可以访问到 dispatch,可以调用 Model 中的 Reducer 或者 Effects.

Reducer

Reducer函数接受两个参数:之前已经累积运算的结果和当前要被累积的值,返回的是一个新的累积结果。该函数把一个集合归并成一个单值。

  • 在 dva 中,reducers 聚合积累的结果是当前 model 的 state 对象。通过 actions 中传入的值,与当前 reducers 中的值进行运算获得新的值(也就是新的 state)。

Effect

Effect 被称为副作用,在我们的应用中,最常见的就是异步操作。

  • 它来自于函数编程的概念,之所以叫副作用是因为它使得我们的函数变得不纯,同样的输入不一定获得同样的输出。

  • dva 为了控制副作用的操作,将异步转成同步写法,从而将effects转为纯函数

Subscription

Subscriptions 是一种从 获取数据的方法,它来自于 elm。

  • Subscription 语义是订阅,用于订阅一个数据源,然后根据条件 dispatch 需要的 action。

数据流图

  • State 是储存数据的地方,收到 Action 以后,会更新数据。

  • View 就是 React 组件构成的 UI 层,从 State 取数据后,渲染成 HTML 代码。只要 State 有变化,View 就会自动更新。

  • Action 是用来描述 UI 层事件的一个对象。

    1
    2
    3
    4
    dispatch({
    type: 'click-submit-button',
    payload: this.form.data
    })
  • connect 是一个函数,绑定 State 到 View。

    1
    2
    3
    4
    5
    6
    import { connect } from 'dva';

    function mapStateToProps(state) {
    return { todos: state.todos };
    }
    connect(mapStateToProps)(App);

    connect 方法返回的也是一个 React 组件,通常称为容器组件。因为它是原始 UI 组件的容器,即在外面包了一层 State。

  • dispatch 是一个函数方法,用来将 Action 发送给 State。

    被 connect 的 Component 会自动在 props 中拥有 dispatch 方法。

数据流图二

Model 对象的属性

每个model,实际上都是普通的JavaScript对象

  • namespace: 当前 Model 的名称。整个应用的 State,由多个小的 Model 的 State 以 namespace 为 key 合成

  • state: 该 Model 当前的状态。数据保存在这里,直接决定了视图层的输出

  • reducers: Action 处理器,处理同步动作,用来算出最新的 State

  • effects:Action 处理器,处理异步动。dva 提供多个 effect 函数内部的处理函数,比较常用的是 callput

    • call:执行异步函数
    • put:发出一个 Action,类似于 dispatch
  • subscriptions

Passing Data Between Adjacent Components

If you have components that are siblings and need to share data, the way to do that in React is to pull that data up into a parent component and pass it down with props.

That can be cumbersome though. Redux can help by giving you one global “parent” where you can store the data, and then you can connect the sibling components to the data with React-Redux.

redux vs react-redux

redux knows nothing about React at all. (The redux library can be used outside of a React app too. It’ll work with Vue, Angular, and even backend Node/Express apps.)

react-redux lets you connect pieces of the state to React components.

store

in charge for orchestrating all the interactions

the state is the data, and the store is where it’s kept.

reducer

the producer to make the state

(state, action) => newState

1
2
3
4
5
6
7
8
9
10
11
12
var letters = ['r', 'e', 'd', 'u', 'x'];

// `reduce` takes 2 arguments:
// - a function to do the reducing (you might say, a "reducer")
// - an initial value for accumulatedResult
var word = letters.reduce(
function(accumulatedResult, arrayItem) {
return accumulatedResult + arrayItem;
},
''); // <-- notice this empty string argument: it's the initial value

console.log(word) // => "redux"

**Important Rule of Reducers **:

  • Never return undefined from a reducer.
  • Reducers must be pure functions.(This means that they can’t modify their arguments, and they can’t have side effects.)

action

plain JavaScript objects with a property named type.

An action object describes a change you want to make (like “please increment the counter”) or an event that happenend (like “the request to the server failed with this error”).

action don’t really do anything. Not on their own, anyway.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
type: "add an item",
item: "Apple"
}

or

{
type: 7008
}

or

{
type: "INCREMENT"
}

In order to make an action DO something, you need to dispatch it.


redux tips

Redux avoids these problems with some simple rules.

  • State is read-only, and actions are the only way to modify it.
  • Changes happen one way, and one way only: dispatch(action) -> reducer -> new state.
  • The reducer function must be “pure” – it cannot modify its arguments, and it can’t have side effects.

The most important methods.

  • getState for accessing the current state of the application
  • dispatch for dispatching an action
  • subscribe for listening on state changes

react-redux

Provider

By wrapping the entire app with the Provider component, every component in the app tree will be able to access the Redux store if it wants to.

connect

all of components can access the Redux store, but not automatically , We’ll need to use the connect function on our components to access the store.

connects a React component with the Redux store.

  • the mapStateToProps function
  • the mapDispatchToProps function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";

import { connect } from "react-redux";

class App extends Component {
render() {
const { fetching, dog, onRequestDog, error } = this.props;

return (
<div className="App">
......
</div>
);
}
}

const mapStateToProps = state => {
return {
fetching: state.fetching,
dog: state.dog,
error: state.error
};
};

const mapDispatchToProps = dispatch => {
return {
onRequestDog: () => dispatch({ type: "API_CALL_REQUEST" })
};
};

export default connect(mapStateToProps, mapDispatchToProps)(App);

redux-thunk

It is a middleware, basically a plugin for Redux, that enables Redux to deal with actions like getUser(), ie.dispatch(getUser())

thunk: it’s an action creator that returns a function instead of a plain action object, like this:

1
2
3
4
5
6
7
function doStuff() {
return function(dispatch, getState) {
// dispatch actions here
// or fetch data
// or whatever
}
}

the 2 agruments in return function,Most of the time you’ll only need dispatch, but sometimes you want to do something conditionally, based on some value in the Redux state. In that case, call getState() and you’ll have the entire state to read as needed.

setup redux thunk

1
2
3
4
5
6
7
8
9
10
11
import thunk from 'redux-thunk';
import { createStore, applyMiddleware } from 'redux';

function reducer(state, action) {
// ...
}

const store = createStore(
reducer,
applyMiddleware(thunk)
);

redux-saga

redux-saga relies on generators, but does a decent amount of the work for us, so (in my fairly limited experience) a deep understanding of them for this use-case isn’t necessary.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { takeLatest, call, put } from "redux-saga/effects";
import axios from "axios";

// watcher saga: watches for actions dispatched to the store, starts worker saga
export function* watcherSaga() {
yield takeLatest("API_CALL_REQUEST", workerSaga);
}

// function that makes the api request and returns a Promise for response
function fetchDog() {
return axios({
method: "get",
url: "https://dog.ceo/api/breeds/image/random"
});
}

// worker saga: makes the api call when watcher saga sees the action
function* workerSaga() {
try {
const response = yield call(fetchDog);
const dog = response.data.message;

// dispatch a success action to the store with the new dog
yield put({ type: "API_CALL_SUCCESS", dog });

} catch (error) {
// dispatch a failure action to the store with the error
yield put({ type: "API_CALL_FAILURE", error });
}
}

Let

let is similar to var but let has scope. let is only accessible in the block level it is defined.

example:

1
2
3
4
5
if (true) {
let a = 40;
console.log(a); //40
}
console.log(a); // undefined

and

1
2
3
4
5
6
7
8
9
10
let a = 50;
let b = 100;
if (true) {
let a = 60;
var c = 10;
console.log(a/c); // 6
console.log(b/c); // 10
}
console.log(c); // 10
console.log(a); // 50

Const

Const is used to assign a constant value to the variable. And the value cannot be changed. Its fixed.

example:

1
2
3
4
const a = 50;
a = 60; // shows error. You cannot change the value of const.
const b = "Constant variable";
b = "Assigning new value"; // shows error.

Whenever you define a const variable, Javascript references the address of the value to the variable.

example:

1
2
3
4
const LANGUAGES = ['Js', 'Ruby', 'Python', 'Go'];
LANGUAGES = "Javascript"; // shows error.
LANGUAGES.push('Java'); // Works fine.
console.log(LANGUAGES); // ['Js', 'Ruby', 'Python', 'Go', 'Java']

the variable ‘LANGUAGES’ actually references to the memory allocated to the array. So you cannot change the variable to reference some other memory location later. Throughout the program it only references to the array.

Arrow Function

1
2
3
4
5
6
7
8
// Old Syntax
function oldOne() {
console.log("Hello World..!");
}
// New Syntax
var newOne = () => {
console.log("Hello World..!");
}

and

1
2
3
4
let NewOneWithParameters = (a, b) => {
console.log(a+b); // 30
}
NewOneWithParameters(10, 20);

There are two things to explain here.

  1. If you have a function with single parameter, you don’t need (). In our case element is the parameter.
  2. And If you have single line as the body of the function you don’t need {} and also JS will implicitly returns the value after executing the function. You don’t have to use return keyword.
  3. Arrow functions shine best with anything that requires this to be bound to the context, and not the function itself.

For of loop

for..of iterates through list of elements (i.e) like Array and returns the elements (not their index) one by one.

1
2
3
4
5
6
7
8
9
let arr = [2,3,4,1];
for (let value of arr) {
console.log(value);
}
Output:
2
3
4
1

and

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let string = "Javascript";
for (let char of string) {
console.log(char);
}
Output:
J
a
v
a
s
c
r
i
p
t

Spread attributes

1
2
3
4
5
6
7
8
9
10
11
let SumElements = (arr) => {
console.log(arr); // [10, 20, 40, 60, 90]

let sum = 0;
for (let element of arr) {
sum += element;
}
console.log(sum); // 220.
}

SumElements([10, 20, 40, 60, 90]);

consider the same example with spread attributes:

1
2
3
4
5
6
7
8
9
let SumElements = (...arr) => {
console.log(arr); // [10, 20, 40, 60, 90]
let sum = 0;
for (let element of arr) {
sum += element;
}
console.log(sum); // 220.
}
SumElements(10, 20, 40, 60, 90); // Note we are not passing array here. Instead we are passing the elements as arguments.

Math.max is a simple method that returns the maximum element from given list. It doesn’t accept an array.

1
2
let arr = [10, 20, 60];
Math.max(arr); // Shows error. Doesn't accept an array.

So lets use our savior:

1
2
let arr = [10, 20, 60];
Math.max(...arr); // 60

Maps

Map holds key-value pairs. It’s similar to an array but we can define our own index. And indexes are unique in maps.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var map = new Map();
map.set('name', 'John');
map.set('id', 10);

map.get('name'); // John
map.get('id'); // 10

map.size; // 2. Returns the size of the map.
map.keys(); // outputs only the keys.
map.values(); // outputs only the values.

for (let key of map.keys()) {
console.log(key);
}
Output:
name
id

for (let [key, value] of map) {
console.log(key+" - "+value);
}
Output:
name - John
id - 10

Sets

Sets are used to store the unique values of any type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var sets = new Set();
sets.add('a');
sets.add('b');
sets.add('a'); // We are adding duplicate value.
for (let element of sets) {
console.log(element);
}
Output:
a
b

sets.size; // returns 2. Size of the set.
sets.has('a'); // returns true.
sets.has('c'); // returns false.

Static methods

1
2
3
4
5
6
7
8
class Example {
static Callme() {
console.log("Static method");
}
}
Example.Callme();
Output:
Static method

you can call the function without creating any instance for the class.

Getters and Setters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class People {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
setName(name) {
this.name = name;
}
}
let person = new People("Jon Snow");
console.log(person.getName());
person.setName("Dany");
console.log(person.getName());
Output:
Jon Snow
Dany

Promises

They are used to make async operations such as API request, file handling, downloading images, etc.

Before promises, programmers used to define callbacks. Callbacks are normal functions in Javascript which executes when the async operation is complete.

  • three states in promises

    1. Pending: In this state the promise is just executing the async operation. For example, It’s making some API request to the server or downloading some images from cdn. from this state promise can move to either to Fulfilled or to Rejected
    2. Fulfilled: If the promise has reached this state, then it means that the async operation is complete and we have the output. For example, we have the response from the API.
    3. Rejected: If the promise has reached this state, it means that the async operation is not successful and we have the error which caused the operation to fail.
    1
    2
    3
    4
    5
    6
    7
    8
    const apiCall = new Promise(function(resolve, reject) {
    if ( API request to get some data ) {
    resolve("The request is successful and the response is "+ response);
    }
    else {
    reject("The request is not successful. The error is "+error);
    }
    });

    Then the resolve function is called if we get the response from the server. And if there is some error reject function is called with the error message.

  • We use handlers to get the output from the promise.

    Handlers are just functions which executes when some event occurs such as clicking a button, moving the cursor, etc.

    So we can use handlers to handle when the resolve function is called or **reject **function is called.

    • The handler then executes its function parameter when the resolve function is called inside the promise.
    1
    2
    3
    4
    5
    6
    // calling the promise with some handlers.
    apiCall.then(function(x) {console.log(x); })

    // Output
    The request is successful and the response is {name: "Jon Snow"}

    • Catch handler looks out for reject function.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    apiCall
    .then(function(x) {
    console.log(x);
    })
    .catch(function(x) {
    console.log(x);
    })

    // Assuming the request is not successful ( reject function is called in the promise. )
    Output:
    The request is not successful

Async / Await

async

1
2
3
async function hello() {
return "Hello Promise..!"
}

The above code is equivalent to the below code:

1
2
3
4
5
function hello() {
return new Promise(function(resolve, reject) {
// executor function body.
});
}

example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
async function hello(a, b) {
if (a < b) {
return "Greater";
}
else {
return new Error("Not Greater");
}
}
hello(14, 10)
.then(function(x) {
console.log("Good..! " + x);
})
.catch(function(x) {
console.log("Oops..! " + x);
})
Output:
Oops..! Not Greater.
// if you call hello(4, 10) you get "Good..! Greater"

Don’t forget that async function will return a promise. So of course, you can call resolve and reject function inside async function too.

example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
async function Max(a, b) {
if (a > b) {
return Promise.resolve("Success");
}
else {
return Promise.reject("Error");
}
}
Max(4, 10)
.then(function(x) {
console.log("Good " + x);
})
.catch(function(x) {
console.log("Oops " + x);
});
Output:
Oops Error
// If we pass Max(14, 10) then we should get "Good Success" :)

await

It makes the Javascript to wait until you get the response from the endpoint. And then it resumes the execution.

await can be used only inside async function. It doesn’t work outside async function

1
2
3
4
5
6
7
8
9
10
11
12
13
async function hello() {
let response = await fetch('https://api.github.com/');
// above line fetches the response from the given API endpoint.
return response;
}
hello()
.then(function(x) {
console.log(x);
});
...
...
Output:
Response from the API.

Array

Array Map

1
2
3
4
5
6
7
let arr = [1,2,3,4,5];
let modifiedArr = arr.map(function(element, index, arr) {
return element * 10;
});
console.log(modifiedArr);
Output:
[10, 20, 30, 40, 50]

And also note we have to return some value in the end. Which will be the modified value of that element. If you didn’t return anything then the particular element will be undefined.

One more thing I like to add is the second and third parameter is only optional. Only the first parameter is mandatory. for example :

1
2
3
let modifiedArr = arr.map(function(element) {
return element * 10;
});

write the map operator with arrow functions:

1
2
3
4
5
6
7
8
9
10
11
12
let modifiedArr = arr.map((element, index) => {
console.log("index "+index);
return element * 10;
});
console.log(modifiedArr);
Output:
index 0
index 1
index 2
index 3
index 4
[10, 20, 30, 40, 50]

better:

1
2
let modifiedArr = arr.map(element => element * 10);
console.log(modifiedArr);

Array Filter

1
2
3
4
5
6
7
let arr = [1, 2, 3, 4, 5, 6]
let modifiedArr = arr.filter(function(element, index, array) {
return element % 2 == 0
});
console.log(modifiedArr);
Output:
[2, 4, 6]

try by arrow function:

1
let modifiedAarr = arr.filter((element, index) => element%2 == 0)

we have to return a boolean value for each element of the array. If you won’t return any boolean value at the end then the filter takes it as false and deletes the element.

Array Reduce

Array reduce is used to aggregate all the elements of an array and return a single value.

1
2
3
4
5
6
7
let arr = [1,2,3,4,5,6]
let total= arr.reduce(function(sum, element, index, array) {
return sum + element;
},0);
console.log("total is "+total);
Output:
total is 21

Unlike filter and map, reduce takes a function with four parameters and also a additional element. Unlike filter and map, the first two parameters are mandatory. Other two are optional.

The first parameter is the aggregator element.In our case it’s 0.

Like filter and map you have to return the end result.

write the same code with arrow functions:

1
let totalSum = arr.reduce((sum, element) => element+sum, 0)

Template Literals

1
2
3
4
5
6
7
8
9
let name = "Srebalaji";
let languages = () => {return "Ruby, Js, Java, Python"}
let msg = `My name is ${name}
My age is ${20+3}
And I code in ${languages()}`
Output:
My name is Srebalaji
My age is 23
And I code in Ruby, Js, Java, Python

Imports and Exports

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//app.js
export let name = "Jon"
export let age = 23

//index.js
import {name, age} from './app'
console.log(name);
console.log(age);

//index.html
<script src="./index.js"></script>

Output:
Jon
23

and:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//app.js
let a = 10;
let b = 2;
let sum = () => a+b;
export {a,b}
export default sum

//index.js
import * as variables from './app'
import addition from './app' // default value
console.log(variables.a);
console.log(variables.b);
console.log(addition());

Output:
10
2
12
  1. If you are using * to import values then you have to use alias (i.e) names that will refer to imported values. In our example we have used variables as alias.

  2. Using * to import values doesn’t import default value. You have to import it separately.

    for example:import addition, * as variables from './app'

Destructuring objects and arrays

1
2
3
4
5
6
7
8
9
let person = {firstName: "Jon", lastName: "Snow", age: 23}
const {firstName, lastName, age} = person
console.log(firstName);
console.log(lastName);
console.log(age);
Output:
Jon
Snow
23

Extend and Super

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Person{
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
displayName() {
return `${this.firstName} - ${this.lastName}`;
}
}
class Employee extends Person {
constructor(firstName, lastName, age, salary) {
super(firstName, lastName, age);
this.salary = salary;
}
displaySalary() {
return `${this.salary}`;
}
displayName() {
return super.displayName();
}
displayAge() {
return this.age;
}
}
let manager = new Employee("Jon", "Snow", 23, 100);
console.log(manager.displaySalary());
console.log(manager.displayName());
console.log(manager.displayAge());
Output:
100
Jon Snow
23

And then we have used super keyword to call the constructor of the parent class. And we also have called the method declared in the parent class using super.

Generator functions

  • Generator functions are written using the function* syntax. When called initially, generator functions do not execute any of their code, instead returning a type of iterator called a Generator.
  • When a value is consumed by calling the generator’s next method, the Generator function executes until it encounters the yield keyword.
    • Each yield in a generator basically represents an asynchronous step in a more synchronous/sequential process — somewhat like await in an asyncfunction.
  • The function can be called as many times as desired and returns a new Generator each time, however each Generator may only be iterated once.

some method

  • includes

    construct an array of the items, and use includes:

    1
    ['a', 'b', 'c'].includes('b')


Learn Regex

什么是正则表达式?

正则表达式是一组由字母和符号组成的特殊文本, 它可以用来从文本中找出满足你想要的格式的句子.

一个正则表达式是在一个主体字符串中从左到右匹配字符串时的一种样式.
“Regular expression”这个词比较拗口, 我们常使用缩写的术语”regex”或”regexp”.
正则表达式可以从一个基础字符串中根据一定的匹配模式替换文本中的字符串、验证表单、提取字符串等等.

想象你正在写一个应用, 然后你想设定一个用户命名的规则, 让用户名包含字符,数字,下划线和连字符,以及限制字符的个数,好让名字看起来没那么丑.
我们使用以下正则表达式来验证一个用户名:

以上的正则表达式可以接受 john_doe, jo-hn_doe, john12_as.
但不匹配Jo, 因为它包含了大写的字母而且太短了.

目录

1. 基本匹配

正则表达式其实就是在执行搜索时的格式, 它由一些字母和数字组合而成.
例如: 一个正则表达式 the, 它表示一个规则: 由字母t开始,接着是h,再接着是e.

"the" => The fat cat sat on the mat.

在线练习

正则表达式123匹配字符串123. 它逐个字符的与输入的正则表达式做比较.

正则表达式是大小写敏感的, 所以The不会匹配the.

"The" => The fat cat sat on the mat.

在线练习

2. 元字符

正则表达式主要依赖于元字符.
元字符不代表他们本身的字面意思, 他们都有特殊的含义. 一些元字符写在方括号中的时候有一些特殊的意思. 以下是一些元字符的介绍:

元字符 描述
. 句号匹配任意单个字符除了换行符.
[ ] 字符种类. 匹配方括号内的任意字符.
[^ ] 否定的字符种类. 匹配除了方括号里的任意字符
* 匹配>=0个重复的在*号之前的字符.
+ 匹配>=1个重复的+号前的字符.
? 标记?之前的字符为可选.
{n,m} 匹配num个大括号之前的字符 (n <= num <= m).
(xyz) 字符集, 匹配与 xyz 完全相等的字符串.
| 或运算符,匹配符号前或后的字符.
\ 转义字符,用于匹配一些保留的字符 [ ] ( ) { } . * + ? ^ $ \ |
^ 从开始行开始匹配.
$ 从末端开始匹配.

2.1 点运算符 .

.是元字符中最简单的例子.
.匹配任意单个字符, 但不匹配换行符.
例如, 表达式.ar匹配一个任意字符后面跟着是ar的字符串.

".ar" => The car parked in the garage.

在线练习

2.2 字符集

字符集也叫做字符类.
方括号用来指定一个字符集.
在方括号中使用连字符来指定字符集的范围.
在方括号中的字符集不关心顺序.
例如, 表达式[Tt]he 匹配 theThe.

"[Tt]he" => The car parked in the garage.

在线练习

方括号的句号就表示句号.
表达式 ar[.] 匹配 ar.字符串

"ar[.]" => A garage is a good place to park a car.

在线练习

2.2.1 否定字符集

一般来说 ^ 表示一个字符串的开头, 但它用在一个方括号的开头的时候, 它表示这个字符集是否定的.
例如, 表达式[^c]ar 匹配一个后面跟着ar的除了c的任意字符.

"[^c]ar" => The car parked in the garage.

在线练习

2.3 重复次数

后面跟着元字符 +, * or ? 的, 用来指定匹配子模式的次数.
这些元字符在不同的情况下有着不同的意思.

2.3.1 *

*号匹配 在*之前的字符出现大于等于0次.
例如, 表达式 a* 匹配以0或更多个a开头的字符, 因为有0个这个条件, 其实也就匹配了所有的字符. 表达式[a-z]* 匹配一个行中所有以小写字母开头的字符串.

"[a-z]*" => The car parked in the garage #21.

在线练习

*字符和.字符搭配可以匹配所有的字符.*.
*和表示匹配空格的符号\s连起来用, 如表达式\s*cat\s*匹配0或更多个空格开头和0或更多个空格结尾的cat字符串.

"\s*cat\s*" => The fat cat sat on the concatenation.

在线练习

2.3.2 +

+号匹配+号之前的字符出现 >=1 次.
例如表达式c.+t 匹配以首字母c开头以t结尾,中间跟着任意个字符的字符串.

"c.+t" => The fat cat sat on the mat.

在线练习

2.3.3 ?

在正则表达式中元字符 ? 标记在符号前面的字符为可选, 即出现 0 或 1 次.
例如, 表达式 [T]?he 匹配字符串 heThe.

"[T]he" => The car is parked in the garage.

在线练习

"[T]?he" => The car is parked in the garage.

在线练习

2.4 {}

在正则表达式中 {} 是一个量词, 常用来一个或一组字符可以重复出现的次数.
例如, 表达式 [0-9]{2,3} 匹配最少 2 位最多 3 位 0~9 的数字.

"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0.

在线练习

我们可以省略第二个参数.
例如, [0-9]{2,} 匹配至少两位 0~9 的数字.

如果逗号也省略掉则表示重复固定的次数.
例如, [0-9]{3} 匹配3位数字

"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0.

在线练习

"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0.

在线练习

2.5 (...) 特征标群

特征标群是一组写在 (...) 中的子模式. 例如之前说的 {} 是用来表示前面一个字符出现指定次数. 但如果在 {} 前加入特征标群则表示整个标群内的字符重复 N 次. 例如, 表达式 (ab)* 匹配连续出现 0 或更多个 ab.

我们还可以在 () 中用或字符 | 表示或. 例如, (c|g|p)ar 匹配 cargarpar.

"(c|g|p)ar" => The car is parked in the garage.

在线练习

2.6 | 或运算符

或运算符就表示或, 用作判断条件.

例如 (T|t)he|car 匹配 (T|t)hecar.

"(T|t)he|car" => The car is parked in the garage.

在线练习

2.7 转码特殊字符

反斜线 \ 在表达式中用于转码紧跟其后的字符. 用于指定 { } [ ] / \ + * . $ ^ | ? 这些特殊字符. 如果想要匹配这些特殊字符则要在其前面加上反斜线 \.

例如 . 是用来匹配除换行符外的所有字符的. 如果想要匹配句子中的 . 则要写成 \. 以下这个例子 \.?是选择性匹配.

"(f|c|m)at\.?" => The fat cat sat on the mat.

在线练习

2.8 锚点

在正则表达式中, 想要匹配指定开头或结尾的字符串就要使用到锚点. ^ 指定开头, $ 指定结尾.

2.8.1 ^

^ 用来检查匹配的字符串是否在所匹配字符串的开头.

例如, 在 abc 中使用表达式 ^a 会得到结果 a. 但如果使用 ^b 将匹配不到任何结果. 因为在字符串 abc 中并不是以 b 开头.

例如, ^(T|t)he 匹配以 Thethe 开头的字符串.

"(T|t)he" => The car is parked in the garage.

在线练习

"^(T|t)he" => The car is parked in the garage.

在线练习

2.8.2 `### 号

同理于 ^ 号, $ 号用来匹配字符是否是最后一个.

例如, (at\.)$ 匹配以 at. 结尾的字符串.

"(at\.)" => The fat cat. sat. on the mat.

在线练习

"(at\.)$" => The fat cat. sat. on the mat.

在线练习

3. 简写字符集

正则表达式提供一些常用的字符集简写. 如下:

简写 描述
. 除换行符外的所有字符
\w 匹配所有字母数字, 等同于 [a-zA-Z0-9_]
\W 匹配所有非字母数字, 即符号, 等同于: [^\w]
\d 匹配数字: [0-9]
\D 匹配非数字: [^\d]
\s 匹配所有空格字符, 等同于: [\t\n\f\r\p{Z}]
\S 匹配所有非空格字符: [^\s]
\f 匹配一个换页符
\n 匹配一个换行符
\r 匹配一个回车符
\t 匹配一个制表符
\v 匹配一个垂直制表符
\p 匹配 CR/LF (等同于 \r\n),用来匹配 DOS 行终止符

4. 零宽度断言(前后预查)

先行断言和后发断言都属于非捕获簇(不捕获文本 ,也不针对组合计进行计数).
先行断言用于判断所匹配的格式是否在另一个确定的格式之前, 匹配结果不包含该确定格式(仅作为约束).

例如, 我们想要获得所有跟在 $ 符号后的数字, 我们可以使用正后发断言 (?<=\$)[0-9\.]*.
这个表达式匹配 $ 开头, 之后跟着 0,1,2,3,4,5,6,7,8,9,. 这些字符可以出现大于等于 0 次.

零宽度断言如下:

符号 描述
?= 正先行断言-存在
?! 负先行断言-排除
?<= 正后发断言-存在
?<! 负后发断言-排除

4.1 ?=... 正先行断言

?=... 正先行断言, 表示第一部分表达式之后必须跟着 ?=...定义的表达式.

返回结果只包含满足匹配条件的第一部分表达式.
定义一个正先行断言要使用 (). 在括号内部使用一个问号和等号: (?=...).

正先行断言的内容写在括号中的等号后面.
例如, 表达式 (T|t)he(?=\sfat) 匹配 Thethe, 在括号中我们又定义了正先行断言 (?=\sfat) ,即 Thethe 后面紧跟着 (空格)fat.

"(T|t)he(?=\sfat)" => The fat cat sat on the mat.

在线练习

4.2 ?!... 负先行断言

负先行断言 ?! 用于筛选所有匹配结果, 筛选条件为 其后不跟随着断言中定义的格式.
正先行断言 定义和 负先行断言 一样, 区别就是 = 替换成 ! 也就是 (?!...).

表达式 (T|t)he(?!\sfat) 匹配 Thethe, 且其后不跟着 (空格)fat.

"(T|t)he(?!\sfat)" => The fat cat sat on the mat.

在线练习

4.3 ?<= ... 正后发断言

正后发断言 记作(?<=...) 用于筛选所有匹配结果, 筛选条件为 其前跟随着断言中定义的格式.
例如, 表达式 (?<=(T|t)he\s)(fat|mat) 匹配 fatmat, 且其前跟着 Thethe.

"(?<=(T|t)he\s)(fat|mat)" => The fat cat sat on the mat.

在线练习

4.4 ?<!... 负后发断言

负后发断言 记作 (?<!...) 用于筛选所有匹配结果, 筛选条件为 其前不跟随着断言中定义的格式.
例如, 表达式 (?<!(T|t)he\s)(cat) 匹配 cat, 且其前不跟着 Thethe.

"(?<!(T|t)he\s)(cat)" => The cat sat on cat.

在线练习

5. 标志

标志也叫模式修正符, 因为它可以用来修改表达式的搜索结果.
这些标志可以任意的组合使用, 它也是整个正则表达式的一部分.

标志 描述
i 忽略大小写.
g 全局搜索.
m 多行的: 锚点元字符 ^ $ 工作范围在每行的起始.

5.1 忽略大小写 (Case Insensitive)

修饰语 i 用于忽略大小写.
例如, 表达式 /The/gi 表示在全局搜索 The, 在后面的 i 将其条件修改为忽略大小写, 则变成搜索 theThe, g 表示全局搜索.

"The" => The fat cat sat on the mat.

在线练习

"/The/gi" => The fat cat sat on the mat.

在线练习

修饰符 g 常用于执行一个全局搜索匹配, 即(不仅仅返回第一个匹配的, 而是返回全部).
例如, 表达式 /.(at)/g 表示搜索 任意字符(除了换行) + at, 并返回全部结果.

"/.(at)/" => The fat cat sat on the mat.

在线练习

"/.(at)/g" => The fat cat sat on the mat.

在线练习

5.3 多行修饰符 (Multiline)

多行修饰符 m 常用语执行一个多行匹配.

像之前介绍的 (^,$) 用于检查格式是否是在待检测字符串的开头或结尾. 但我们如果想要它在每行的开头和结尾生效, 我们需要用到多行修饰符 m.

例如, 表达式 /at(.)?$/gm 表示小写字符 a 后跟小写字符 t , 末尾可选除换行符外任意字符. 根据 m 修饰符, 现在表达式匹配每行的结尾.

"/.at(.)?$/" => The fat
                cat sat
                on the mat.

在线练习

"/.at(.)?$/gm" => The fat
                  cat sat
                  on the mat.

在线练习

6. 贪婪匹配与惰性匹配 (Greedy vs lazy matching)

正则表达式默认采用贪婪匹配模式,在该模式下意味着会匹配尽可能长的子串。我们可以使用 ? 将贪婪匹配模式转化为惰性匹配模式。

"/(.*at)/" => The fat cat sat on the mat. 

在线练习

"/(.*?at)/" => The fat cat sat on the mat. 

在线练习

贡献

许可证

MIT © Zeeshan Ahmad

Like any unfamiliar technology, React does have a learning curve. With practice and some patience, you will get the hang of it.

  • React also streamlines how data is stored and handled, using state and props.

create react app

  • npm install -g create-react-app
  • npx create-react-app my-app or npm init react-app my-app

JSX: JavaScript + XML

Babel compiles JSX down to React.createElement() calls.

jsx

1
const heading = <h1 className="site-heading">Hello, React</h1>

non-jsx

1
const heading = React.createElement('h1', { className: 'site-heading' }, 'Hello, React!')

the feature of jsx:

  • className is used instead of class for adding CSS classes, as class is a reserved keyword in JavaScript.
  • Properties and methods in JSX are camelCase - onclick will become onClick.
  • Self-closing tags must end in a slash - e.g. <img />

Components

Whether you declare a component as a function or a class, it must never modify its own props.

Function

The simplest way to define a component is to write a JavaScript function:

1
2
3
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

Class Components

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React, { Component } from 'react'

class Table extends Component {
render() {
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Job</th>
</tr>
</thead>
<tbody>
<tr>
<td>Charlie</td>
<td>Janitor</td>
</tr>
</tbody>
</table>
)
}
}

export default Table

Simple Components

The other type of component in React is the simple component, which is a function. This component doesn’t use the class keyword. Let’s take our Table and make two simple components for it - a table header, and a table body.

1
2
3
4
5
6
7
8
9
10
const TableHeader = () => {
return (
<thead>
<tr>
<th>Name</th>
<th>Job</th>
</tr>
</thead>
)
}
1
2
3
4
5
6
7
8
9
10
const TableBody = () => {
return (
<tbody>
<tr>
<td>Charlie</td>
<td>Janitor</td>
</tr>
</tbody>
)
}
1
2
3
4
5
6
7
8
9
10
class Table extends Component {
render() {
return (
<table>
<TableHeader />
<TableBody />
</table>
)
}
}

Everything should appear as it did before. As you can see, components can be nested in other components, and simple and class components can be mixed.

A class component must include render(), and the return can only return one parent element.

Converting a Function to a Class

convert a function component to a class in five steps:

  1. Create an ES6 class, with the same name, that extends React.Component.
  2. Add a single empty method to it called render().
  3. Move the body of the function into the render() method.
  4. Replace props with this.props in the render() body.
  5. Delete the remaining empty function declaration.

Props

Props are an effective way to pass existing data to a React component, however the component cannot change the props - they’re read-only.

  • props are a way of passing data from parent to child.

State

State is similar to props, but it is private and fully controlled by the component.

State is reserved only for interactivity, that is, data that changes over time.

You can think of state as any data that should be saved and modified without necessarily being added to a database - for example, adding and removing items from a shopping cart before confirming your purchase.

  • You must use this.setState() to modify an array. Simply applying a new value to this.state.property will not work.

    ie.

    1
    2
    // Wrong
    this.state.comment = 'Hello';
    1
    2
    // Correct
    this.setState({comment: 'Hello'});

tips:

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

ie.

1
2
3
4
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});

use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:

1
2
3
4
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));

The Data Flows Down

If you imagine a component tree as a waterfall of props, each component’s state is like an additional water source that joins it at an arbitrary point but also flows down.

Neither parent nor child components can know if a certain component is stateful or stateless, and they shouldn’t care whether it is defined as a function or a class.

This is why state is often called local or encapsulated. It is not accessible to any component other than the one that owns and sets it.

This is commonly called a “top-down” or “unidirectional” data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.

Lifecycle methods

constructor

componentDidMount

The componentDidMount() method runs after the component output has been rendered to the DOM.

componentWillUnmount

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}

componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}

componentWillUnmount() {
clearInterval(this.timerID);
}

tick() {
this.setState({
date: new Date()
});
}

render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}

ReactDOM.render(
<Clock />,
document.getElementById('root')
);

Let’s quickly recap what’s going on and the order in which the methods are called:

  1. When <Clock /> is passed to ReactDOM.render(), React calls the constructor of the Clockcomponent. Since Clock needs to display the current time, it initializes this.state with an object including the current time. We will later update this state.
  2. React then calls the Clock component’s render() method. This is how React learns what should be displayed on the screen. React then updates the DOM to match the Clock’s render output.
  3. When the Clock output is inserted in the DOM, React calls the componentDidMount() lifecycle method. Inside it, the Clock component asks the browser to set up a timer to call the component’s tick() method once a second.
  4. Every second the browser calls the tick() method. Inside it, the Clock component schedules a UI update by calling setState() with an object containing the current time. Thanks to the setState() call, React knows the state has changed, and calls the render() method again to learn what should be on the screen. This time, this.state.date in the render() method will be different, and so the render output will include the updated time. React updates the DOM accordingly.
  5. If the Clock component is ever removed from the DOM, React calls the componentWillUnmount() lifecycle method so the timer is stopped.

总结:constructor->render()->componentDidMount()

state改变->render()

componentWillReceiveProps

componentWillReceiveProps在初始化render的时候不会执行,它会在Component接受到新的状态(Props)时被触发,一般用于父组件状态更新时子组件的重新渲染。

在componentWillReceiveProps中想作任何变更最好都将两个状态进行比较,假如状态有异才执行下一步。不然容易造成组件的多次渲染,并且这些渲染都是没有意义的。

Events

Conditional Rendering

Also remember that whenever conditions become too complex, it might be a good time to extract a component.

  • Returning null from a component’s render method does not affect the firing of the component’s lifecycle methods. For instance componentDidUpdate will still be called.

Lists and Keys

Keep in mind that if the map() body is too nested, it might be a good time to extract a component.

Forms

Lifting State Up

Composition vs Inheritance

  • Remember that components may accept arbitrary props, including primitive values, React elements, or functions.

Thinking in React

  • You can build top-down or bottom-up. That is, you can either start with building the components higher up in the hierarchy or with the ones lower in it. In simpler examples, it’s usually easier to go top-down, and on larger projects, it’s easier to go bottom-up and write tests as you build.
  • Remember: React is all about one-way data flow down the component hierarchy.