/*** Destruct and spread Array, Object */
// Destruct
const {a,b} = {a:1,b:2}
// Destruct and store in foo,bar
const {a:foo, b:bar} = {a:1,b:2}
// Destruct with default value 0
const {a=0, b=0} = {a:1}
// Destruct array
const [a,b] = [1,2]
// Destruct then swap values
let a=1, b=2
[a,b] = [b,a]
// Destruct with default value
let a,b
([a=1,b=2] = [0])
const arr = [{id:1,title:'a'}, {id:2,title:'b'}]
const obj = Object.assign({}, ...arr.map(item => ({[item.id]:item})))
// result: {1:{id:1,title:'a'}, 2:{id:2,title:'b'}}
const obj = {hello:'world', foo:'bar'}
const arr = Object.entries(obj)
// result: [['hello','world'], ['foo','bar']]
/* REVERSE */
const obj2 = Object.fromEntries(arr)
// "Set"
[...new Set(array)]
// "Filter"
array.filter((item,index) => array.indexOf(item) === index)
// "Reduce"
array.reduce((ac, item) => ac.includes(item) ? ac : [...ac, item], [])
let obj = {}
const isObjectAndIsEmpty = obj && Object.keys(obj).length === 0 && obj.constructor === Object
// "indexOf"
array.indexOf('foo') !== -1
// "includes"
array.includes('foo')
// "some"
array.some(item => item === 'foo')
array.some(obj => obj.name.toLowerCase() === 'foo')
const array = ['apple', 'orange', 'banana']
const [,,take] = array // take is 'banana'
const [_,_ignore,take] = array // use _ for useless variable
const [/*apple*/,/*orange*/,take] = array // use of comment
const {length, [length - 1]:last} = array // last is 'banana'
// "flatMap" every callback return array will merge into one result array
const fruits = ['apple', 'banana']
fruits.flatMap((name, index) => [name, index])
// ['apple', 1, 'banana', 2]
Math.pow(2, 3)
2 ** 3
// 2 pow 3 equal 8
/* remove all after decimal point */
23.9 | 0 // 23
-23.9 | 0 // -23
239 / 10 | 0 // 23
239 / 100 | 0 // 2
console.time('flag')
// do something take time
console.timeEnd('flag')
const jsonObject = {foo:'foo', bar:'bar'}
console.log(
JSON.stringify(jsonObject, null, '\t')
)
const numbers = [1,2,3,-1]
const isPositive = (n) => (n > 0)
numbers.every(isPositive) // false
numbers.some(isPositive) // true
arrayItems.map(Number) // cast all array items into Number
arrayItems.map(Boolean) // cast all array items into Boolean