Javascript Advanced
The + Operator
- converting the given expression to a number
+(new Date()) // 1593565210654
+true // 1
+false // 0
+"1e-8" // 100000000
+"1.6e-2" // 0.016
// overriding the valueOf() method of the random object
const random = {
'valueOf': () => Math.floor(Math.random() * 1000)
}
+random // 42
+random // 476
+random // 887
The Comma Operator
- evaluate multiple expressions where JavaScript expects one
let money = 10;
const hasStudied = false;
const relax = () => console.log("relax");
const study = () => console.log("study");
hasStudied ? (money++, relax()) : (money/=2, study()); // study
console.log(money); // 5
for (let i=1, j=2; i+j < 10; i++, j++) {
console.log(i, j);
}
// 1 2
// 2 3
// 3 4
// 4 5
const coins = [
{value:4, currency:"EUR"},
{value:1, currency:"USD"},
{value:5, currency:"BTC"},
]
const countOddCoins = (coins) => {
let oddCoins = 0;
coins.forEach(({ value, currency }) => {
if (value % 2 != 0) {
(oddCoins++, console.log(`${oddCoins} with ${currency}`));
}
})
return oddCoins;
}
console.log(countOddCoins(coins));
// 1 with USD
// 5 with BTC
// 2
The Set Object
- stores unique values of any type, whether primitive values or object references
const arr = [1, 1, 7, 5, 6, 6, 6, 8, 7];
// old way
let noDup = arr.filter((a,b) => arr.indexOf(a) === b);
// new way
noDup = [...new Set(arr)];
console.log(noDup);
// 1 7 5 6 8
let a = new Set("hello world!");
// h e l o w r d !
let b = new Set("medium is cool!");
// m e d i u m s c o l !
const intersection = (a, b) => {
let intersection = new Set();
for (let elem of b) {
if (a.has(elem)) {
intersection.add(elem);
}
}
return intersection;
}
console.log(intersection(a, b));
// e d o l !
The Navigator & Performance API's
const webapi = () => {
// Performance API
const start = performance.now();
const fib = n => {
if(n <= 1) return n;
return fib(n-1) + fib(n-2);
}
fib(15);
const end = performance.now();
console.log(end - start);
// 0.1699999994598329 (on my machine)
// Navigator API
navigator.geolocation.getCurrentPosition(pos => {
const { coords: { latitude, longitude } } = pos;
console.log(latitude, longitude);
// 48.9080891 2.2699974
});
}
recude() map() and filter()
let orders = [1, 2, 3, 4, 5];
const total = orders.reduce((acc, cur) => acc + cur);
console.log(total); // 15
const total2 = orders.map((item) => item*2);
console.log(total2); // 2, 4, 6, 8, 10
const total3 = orders.filter((item) => item > 3);
console.log(total3); // 4, 5
Shuffle Array Elements
const arr = [1, 2, 3, 4, 5];
const shuffled = arr.sort(() => Math.random() - 0.5);