/images/art2.png

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}`);
})

How to demonstrate your front end application on Github by gh-page

Github provide a tech called github pages that can hosted your project directly from repository. Basely push you project into gh-pages branch and the index.html will show on the page which is {<github username>.github.io}/{<repository name>}

gh-pages

gh-pages provide by Tim Schaub is a npm package that can help you push something directly into gh-page branch

Read more detail in repository

command line usage

This package also provide a command line tool:

CSS Overview

CSS cheat sheet: html & css provided by Traversy Media

Font

font-size size

font-family: <FAMILY_NAME>, <GENERIC_NAME>;

font-family: Lobster monospace;

GENERIC_NAME: sans-serif serif monospace;

sans-serif force on connected and serif force on single alphabet.

line-height: 25px;

Import font

Could use google font and add link into index.html or in style.css

Control space

There are three important properties to control the space: padding, margin and border

Border

border-size

border-color

border-width

border-style

border: <border-width> <border-style> <border-color>

Basic Terminal command

Basic

cd route

ls list

pwd show current path

cat concatenate and print file (usually as read file)

touch change file access and modification time; (usually as create file)

Routing

cd <directory>

cd . current

cd .. last

cd ~ home

cd / root

List

ls

ls -a list all included hiding file

ls -l list detail

Move & Copy

cp <name1> <name2> copy

mv <name1> <name2> rename

move one file within this directory to another name.

How to check the Chinese ID is correct

This check method will help you find out whether one digit is wrong or 2 adjacent digit are in reverse order.

Sample code

checkChineseId = (id) => {
    const ID_LENGTH = 18;
    // check type
    if (typeof id !== 'string') {
        console.error('type error');
        return;
    }

    //check length
    if (id.length !== ID_LENGTH) {
        console.error('length error');
        return;
    }

    // check each digit
    for (let i = 0; i < id.length - 1; i++) {
        const e = id[i];
        if (e < '0' || e > '9') {
            console.error('digit error');
            return;
        }
    }

    if (
        id[ID_LENGTH - 1] !== 'x' &&
        id[ID_LENGTH - 1] != 'X' &&
        id[ID_LENGTH - 1] < '0' &&
        id[ID_LENGTH - 1] > '9'
    ) {
        console.error('digit error');
        return;
    }
    //   num: 01 01 00 01 00 05 01 09 04 09 01 02 03 01 00 00 02 10
    //serial: 17 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00
    //weight = 2^serial % 11
    //weight: 07 09 10 05 08 04 02 01 06 03 07 09 10 05 08 04 02 01 (fix)
    // calculate code
    let weight_sum = 0;
    for (let i = 0; i < id.length - 1; i++) {
        let weight = Math.pow(2, ID_LENGTH - 1 - i) % 11;
        weight_sum += id[i] * weight;
    }
    // checkCode = (12 - weight_sum % 11) % 11
    let checkCode = (12 - (weight_sum % 11)) % 11;
    // compare
    let res = false;
    if (checkCode == 10) {
        res =
            id[ID_LENGTH - 1] === 'x' || id[ID_LENGTH - 1] === 'X'
                ? true
                : false;
    } else {
        res = id[ID_LENGTH - 1] == checkCode ? true : false;
    }

    console.log(`${id} is ${res}`);
    return res;
};

module.exports = {
    checkChineseId,
};

Structured binding

Structured binding is a new feature since c++17

cppreference.com

auto [ identifier-list ] = expression

Bind array

 int main(int argc, char const *argv[])
{
	int test[3] = {1, 2, 3};

	auto [a, b, c] = test; // an new array e copy from test and a = e[0]; b = e[1]; c = e[2];
	auto &[x, y, z] = test; // x = test[0]; x = test[1]; x = test[2]

	cout << ++a << " " << ++b << " " << ++c << " " << endl;
	for (int &i : test)
		cout << i << " ";
	cout << endl;

	cout << ++x << " " << ++y << " " << ++z << " " << endl;
	for (int &i : test)
		cout << i << " ";
	cout << endl;

	return 0;
}

tuple

int main(int argc, char const *argv[])
{
	tuple<int, int, int> test(1, 2, 3);

	auto &[a, b, c] = test; // 1 2 3

	pair<int, char> test2(1, 'c');

	auto &[a2, b2] = test2; // 1 c

	return 0;
}

struct

struct test
{
    int a;
    int b;
};

int main(int argc, char const *argv[])
{

    test one;
    one.a = 1;
    one.b = 2;

    auto &[first, second] = one; // 1 ,2

    return 0;
}

Traverse a tree

Idea to traverse a tree

Tree structure

The tree structure:

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

BFS DFS Pre-order In-order Post-order

Relationship:

/images/2020-02-10-traverse-a-tree/145_transverse.png

Iterative

Loop for BFS:

void BFS(TreeNode *root){
    stack<TreeNode *> q;
    q.push(root);
    while(!q.empty()){
        TreeNode *temp = q.front();
        q.pop();
        // do something
        if(temp->left != NULL) q.push(temp -> left);
        if(temp->right != NULL) q.push(temp -> right);
    }
}

Loop for DFS:

How to find next permutation

This is introduce how to find the next lexicographically permutation.

Suppose the permutation is 1 2 3. The next one is 1 3 2.

Algorithm in C++

C++ provide an algorithm called next_permutation to support that. Reference

Example:

#include <iostream>     // std::cout
#include <algorithm>    // std::next_permutation, std::sort

int main () {
  int myints[] = {1,2,3};

  std::sort (myints,myints+3);

  std::cout << "The 3! possible permutations with 3 elements:\n";
  do {
    std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
  } while ( std::next_permutation(myints,myints+3) );

  std::cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';

  return 0;

How it work.

There are four step to achieve.