/images/art2.png

Js Trick

warning
Many of JavaScript cool feature or syntactic sugar included since ES6(ES2015).

You can read this Article to know What new feature brings in since ES6

Conversion

Any => Boolean

!!false; // false
!!undefined; // false
!!null; // false
!!NaN; // false
!!0; // false
!!''; // false

!!variable == Boolean(variable);

String => Integer

Number('100'); //100
+'100'; // 100

+'abc'; // NAN

Object <=> Array

Array => Object

let arr = [1, 2, 3, 4, 5];

let objFromArr1 = Object.assign({}, arr);

let objFromArr2 = { ...arr };

console.log(objFromArr1); // { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }

console.log(objFromArr2); // { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }

let pair = [
  ['key1', 'val1'],
  ['key2', 'val2'],
]; // Map works as well

let objFromPair = Object.fromEntries(arr); // ES10

console.log(objFromPair); //{ key1: 'val1', key2: 'val2' }

Object.fromEntries(arr) included in ES10 (ES2019). Before ES10 or convert a complex array, arr.reduce(()=>{}, {}) is a good method

Python Overview

This posts only use as a remainder

Variable

Multiple assignment

x, y, name, is_cool = (1, 2.5, 'a name', True)

Casting

x = str(x)
# x will be string
y = int(y)
# y will be an integer

String

name = 'Brad'
age = 37

print('name is' + name + ' and age is ' + str(age))
print('name is {name} and age is {age}'.format(name = name, age = age))
print(f'name is {name} and age is {age}')

Methods

# Capitalize string
print(s.capitalize())

# Make all uppercase
print(s.upper())

# Make all lower
print(s.lower())

# Swap case
print(s.swapcase())

# Get length
print(len(s))

# Replace
print(s.replace('world', 'everyone'))

# Count
sub = 'h'
print(s.count(sub))

# Starts with
print(s.startswith('hello'))

# Ends with
print(s.endswith('d'))

# Split into a list
print(s.split())

# Find position
print(s.find('r'))

# Is all alphanumeric
print(s.isalnum())

# Is all alphabetic
print(s.isalpha())

# Is all numeric
print(s.isnumeric())

List

A List is a collection which is ordered and changeable. Allows duplicate members.

chmod Overview

chmod is linux command to control file permission

usage

chmod [u|g|o|a][=|+|-] [r|w|x]

u => user

g => group

o => other

a => all

r => read

w => write

x => execute

example

chmod +wr test.txt give write and read permission for user

chmod -r test.txt remove read permission for user

chmod g=wrx test.txt give write, read and execute permission for group

use number

specific the bits 011101110111 => -rwx-rwx-rwx

SocketIo Overview

socket.io enable realtime, bidirectional communication for Nodejs

Backend

We use Express as backend framework.

const express = require('express');
const path = require('path');
const http = require('http');
const socket_io = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socket_io(server);

io.on('connection', (server_socket) => {
    // ...
}

Frontend

  1. bring client side socket.io in your html file
<script src="/socket.io/socket.io.js"></script>
  1. connect in your frontend script file
const clientSocket = io();

Function

Receive -> on()

socket.on('<head>', (data) => {
    // deal with data
});

Send -> emit()

socket.emit('<head>', data);

Send to all client socket except itself -> socket.broadcast.emit()

socket.broadcast.emit('<head>', data);

Sent to all client socket include itself -> io.emit()

io.emit('<head>', data);

Group socket together

socket.join('<name>');

Send to a group

socket.to('<name>').emit();
socket.broadcast.to('<name>').emit();
io.to('<name>').emit();

SSH Overview

ssh-keygen

ssh-keygen

-b specific the number of bits(1024 2048 4069)

-m specific type

-y get public key

-f specific file name

public key

public key should give to server. Usually put in file ~/.ssh/authorized_key

access via SSH

ssh <username>@<hostname | ip address>

Heroku overview

Heroku can help us deploy our application(back end) rapidly and easy

deploy

The only we need to take care is the PORT of your app. You have to use the PORT in environment.

In Node.js

PORT = process.env.PORT || 3000; // 3000 can be anything else

heroku cli

Home page

heroku login

heroku create

All String Method in Javascript

Show all function: Try String.prototype & String in browser console.

fromCharCode

console.log(String.fromCharCode(189, 43, 190, 61));
// expected output: "½+¾="

fromCodePoint

console.log(String.fromCodePoint(9731, 9733, 9842, 0x2f804));
// expected output: "☃★♲你"

raw

// Create a variable that uses a Windows
// path without escaping the backslashes:
const filePath = String.raw`C:\Development\profile\aboutme.html`;

console.log(`The file was uploaded from: ${filePath}`);
// expected output: "The file was uploaded from: C:\Development\profile\aboutme.html"

charAt

const sentence = 'The quick brown fox jumps over the lazy dog.';

const index = 4;

console.log(`The character at index ${index} is ${sentence.charAt(index)}`);
// expected output: "The character at index 4 is q"

charCodeAt

const sentence = 'The quick brown fox jumps over the lazy dog.';

const index = 4;

console.log(
    `The character code ${sentence.charCodeAt(
        index
    )} is equal to ${sentence.charAt(index)}`
);
// expected output: "The character code 113 is equal to q"

codePointAt

const icons = '☃★♲';

console.log(icons.codePointAt(1));
// expected output: "9733"

concat

const str1 = 'Hello';
const str2 = 'World';

console.log(str1.concat(' ', str2));
// expected output: "Hello World"

console.log(str2.concat(', ', str1));
// expected output: "World, Hello"

startsWith

const str1 = 'Saturday night plans';

console.log(str1.startsWith('Sat'));
// expected output: true

console.log(str1.startsWith('Sat', 3));
// expected output: false

console.log(str1.startsWith('ur', 3));
// true

endsWith

const str1 = 'Cats are the best!'; // len == 18

console.log(str1.endsWith('best', 17));
// expected output: true

const str2 = 'Is this a question';

console.log(str2.endsWith('?'));
// expected output: false

includes

const sentence = 'The quick brown fox jumps over the lazy dog.';

const word = 'fox';

console.log(
    `The word "${word}" ${
        sentence.includes(word) ? 'is' : 'is not'
    } in the sentence`
);
// expected output: "The word "fox" is in the sentence"

indexOf

const paragraph =
    'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);

console.log(
    `The index of the first "${searchTerm}" from the beginning is ${indexOfFirst}`
);
// expected output: "The index of the first "dog" from the beginning is 40"

console.log(
    `The index of the 2nd "${searchTerm}" is ${paragraph.indexOf(
        searchTerm,
        indexOfFirst + 1
    )}`
);
// expected output: "The index of the 2nd "dog" is 52"

lastIndexOf

const paragraph =
    'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

const searchTerm = 'dog';

console.log(
    `The index of the first "${searchTerm}" from the end is ${paragraph.lastIndexOf(
        searchTerm
    )}`
);
// expected output: "The index of the first "dog" from the end is 52"

localeCompare

const a = 'réservé'; // with accents, lowercase
const b = 'RESERVE'; // no accents, uppercase

console.log(a.localeCompare(b));
// expected output: 1
console.log(a.localeCompare(b, 'en', { sensitivity: 'base' }));
// expected output: 0

match

const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
const found = paragraph.match(regex);

console.log(found);
// expected output: Array ["T", "I"]

matchAll

The matchAll() method returns an iterator of all results matching a string against a regular expression, including capturing groups.

All array method in Javascript

Show all function: Try Array.prototype & Array in browser console.

foreach

let numbers = [1, 2, 3, 4, 5];
// each element in a func
numbers.forEach((element, index, arr) => {
    console.log(`a[${index}] = ${element}`);
});
// a[0] = 1
// a[1] = 2
// a[2] = 3
// a[3] = 4
// a[4] = 5

map

let numbers = [1, 2, 3, 4, 5];

// [] => [] (some size)
let numbers2 = numbers.map((e, index, arr) => {
    return e * index;
});
console.log(numbers2); // [0, 2, 6, 12, 20]

filter

let numbers = [1, 2, 3, 4, 5];
// [] => fuc => [] (some left)
let numbers3 = numbers.filter((e, index, arr) => {
    return arr.indexOf(e) === index;
}); // remove duplication

reduce

let numbers = [1, 2, 3, 4, 5];
// [] => 1
let numbers4 = numbers.reduce((prev, cur, curIndex, arr) => {
    return prev + cur;
}, 0);
console.log(numbers4); // 15

let maxValue = numbers.reduce((prev, cur) => {
    if (prev > cur) return prev;
    else return cur;
}, -Infinity);
console.log(maxValue); // 5

slice

let numbers = [1, 2, 3, 4, 5];
// [start, end)
// [start to end)
let first2 = numbers.slice(0, 2);
let shallowCopy = numbers.slice(); // could shallow copy an array
shallowCopy[5] = 100;
let last3 = numbers.slice(-3);
let startFrom1 = numbers.slice(1);
console.log([first2, shallowCopy, last3, startFrom1]);
// [ [ 1, 2 ], [ 1, 2, 3, 4, 5, 100 ], [ 3, 4, 5 ], [ 2, 3, 4, 5 ] ]

splice

let numbers = [1, 2, 3, 4, 5];

let deleted = numbers.splice(1, 2, 'add', 'add'); // (start point, num, ...add-in)
console.log(numbers, deleted);
//[ 1, 'add', 'add', 4, 5 ] [ 2, 3 ]

sort

let numbers = [75, 22, 18, 10, 100, 214, 1];
numbers.sort(); // not sort by number
// If compareFn not provided, sort everything base on string.
console.log(numbers); // [1, 10, 100, 18, 214, 22,  75]

// CompareFn return a Number. If return < 0, a goes first. If return > 0, b goes first. If return 0, not change
numbers.sort((a, b) => {
    return a - b; // if use a > b, function only return 0 and 1.
});
console.log(numbers); // [ 1, 10, 18, 22, 75, 100, 214]

concat

let a = [1, 2, 3];
let b = [10, 20, 30];
let c = a.concat(b);
let d = a.concat(c, 100, a);
console.log(c); // [ 1, 2, 3, 10, 20, 30 ]
console.log(d); // [ 1, 2, 3, 1, 2, 3, 10, 20, 30, 100, 1, 2, 3]
shallowCopy = d.concat(); // also a shallow copy

fill

let numbers = [1, 2, 3, 4, 5];
// fill
let out = numbers.fill(0, 2, 4); // (value, start, end)
console.log(out); // [ 1, 2, 0, 0, 5 ]
console.log(numbers); // [ 1, 2, 0, 0, 5 ]
let fillInNumber = (n) => {
    return Array(n)
        .fill(0)
        .map((_, idx) => idx);
};
console.log(fillInNumber(10)); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

include

let names = ['andy', 'bob', 'eve'];
console.log(names.includes('bob')); // true

join

let names = ['andy', 'bob', 'eve'];

let res = names.join();
console.log(res); // andy,bob,eve
res = names.join(' - ');
console.log(res); // andy - bob - eve

reverse

let names = ['andy', 'bob', 'eve'];
let str = 'coding is fun';
res = str.split(' ').reverse().join(' ');
console.log(res); // fun is coding

push

let numbers = [0];

let len = numbers.push(1, 2, 3, 4, 5);
console.log(len); // 6
console.log(numbers); // [ 0, 1, 2, 3, 4, 5 ]

pop

let numbers = [1, 2, 3, 4, 5];

let lastItem = numbers.pop();
console.log(lastItem); // 5
console.log(numbers); // [1,2,3,4]

unshift

let numbers = [1, 2, 3, 4, 5];

len = numbers.unshift(-1, -2); // push at begin
console.log(len); // 7
console.log(numbers); // [-1, -2, 1, 2, 3, 4, 5]

shift

let numbers = [1, 2, 3, 4, 5];
let res = numbers.shift();
console.log(res, numbers); // 1 [2, 3, 4, 5]

indexOf & lastIndexOf

let names = ['florin', 'ivan', 'liam', 'ivan', 'liam'];

let idx = names.indexOf('jay');

console.log(idx); // -1

idx = names.indexOf('liam'); // return first index

console.log(idx); // 2

idx = names.lastIndexOf('liam');

console.log(idx); // 4

every

let numbers = [1, 2, 3, 4, 5];
// each => bool
let res = numbers.every((each) => {
    return each > 0;
});

console.log(res); // true

const people = [{ name: '1' }, { name: '1' }, { name: '1' }, { surname: '1' }];
res = people.every((each) => each.name !== undefined);
console.log(res); // false

some

let numbers = [1, 2, 3, 4, 5];

let res = numbers.some((each) => {
    return each > 4;
});

console.log(res); // true

find

let people = [
    {
        name: 'florin',
        age: 25,
    },
    {
        name: 'ivan',
        age: 20,
    },
    {
        name: 'lima',
        age: 18,
    },
];

let res = people.find((each) => {
    return each.name == 'ivan';
}).age;

console.log(res); // 20

findIndex

const numbers = [1, 2, 3, 4, 5];

let res = numbers.findIndex((each) => {
    return each === 4;
});

console.log(res); // 3

flat

let array = [1, [2, [3, [4, [5]]]]];

console.log(array.flat()); // [1, 2, [3, [4, [5]]]]
console.log(array.flat(3)); // [1, 2, 3, 4, [5]]
console.log(array.flat(Infinity)); // [1, 2, 3, 4, 5]

flatMap

keys & values & entries

These 3 methods returns a new Array Iterator object

Express Overview

Express.js is a web framework for Node.js

Example

const express = require('express');

const app = express();

app.use(...); // get and post or middle ware

app.get('/', (req, res) => {
    return res.send({hello:"world"});
})

const PORT = 4000;
app.listen(PORT, ()=> {
    console.log(`Server is ready on http://localhost:${PORT}`);
})