Collection of JS tips and tricks
Last active
June 9, 2020 02:53
-
-
Save kiichi/7cf7f71f1e2c28a9e53f6f43ed3faed1 to your computer and use it in GitHub Desktop.
Javascript Tips
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Flatterning Array | |
var arr = [[1,2,3],[1,3,4]]; | |
[].concat(...arr) | |
// [1, 2, 3, 1, 3, 4] | |
// Flattening Array - 2 levels | |
arr = [[[5,6,2],[5,6,2]],[[5,6,2],[5,6,2]]]; | |
flattern = [].concat(...[].concat(...a)); | |
//[5, 6, 2, 5, 6, 2, 5, 6, 2, 5, 6, 2] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const login = async (payload) => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if (payload){ | |
if (payload.username === 'admin' && payload.password == 'admin'){ | |
resolve({status:"ok",message:"",token:"123"}); | |
} | |
else { | |
reject(new Error("Invalid Username or Password")); | |
} | |
} | |
else { | |
reject(new Error("Server side error")); | |
} | |
}, 2000); | |
}); | |
}; | |
// Example Usage - just like regular HTTP Call, this will simulate certain delay | |
try { | |
const res = await login({username:"admin",password:"admin"}); | |
console.log('success!',res.token); | |
} | |
catch(err){ | |
console.log('error!',err.message); | |
} | |
// Example 2 - Promise All | |
await Promise.all([login({username:"admin",password:"admin"}), | |
login({username:"admin",password:"admin"}), | |
login({username:"admin",password:"admin"})]); | |
// array results | |
await Promise.all([login({username:"admin",password:"admin"}), | |
login({username:"admin",password:"x"}), | |
login()]); | |
// VM963:10 Uncaught Error: Invalid Username or Password |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var debounce = (function () { | |
var debTimer = 0; | |
return function (callback, ms) { | |
clearTimeout(debTimer); | |
debTimer = setTimeout(callback, ms); | |
}; | |
})(); | |
debounce(function(){console.log('hello but only last one execute')},1000); | |
debounce(function(){console.log('hello but only last one execute')},1000); | |
debounce(function(){console.log('hello but only last one execute')},1000); | |
debounce(function(){console.log('hello but only last one execute')},1000); | |
debounce(function(){console.log('hello but only last one execute')},1000); | |
debounce(function(){console.log('hello but only last one execute')},1000); | |
// hello but only last one execute |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let dict = {}; | |
a['hello'] = "world"; | |
let b = {}; | |
b['one'] = "two"; | |
// Merging: Using Spread | |
let merged = {...a,...b} | |
console.log(merged); | |
// Merging: Using Assign | |
let merged2 = Object.assign({}, a, b); | |
console.log(merged2); | |
// Looping through dictionary | |
Object.entries({one:"two",three:"four",five:"six"}) | |
// 0: (2) ["one", "two"] | |
// 1: (2) ["three", "four"] | |
// 2: (2) ["five", "six"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// From Array to Dictionary (e.g. "Name" property is unique key in this case | |
var arr = [ | |
{"Key":"ABC123","Address":"1 Main st"}, | |
{"Key":"ABC124","Address":"3 Jackson Ave"}, | |
{"Key":"ABC125","Address":"P.O Box 123"} | |
]; | |
var dict = arr.reduce((map, obj) => { | |
map[obj.Key] = obj; | |
return map; | |
}, {}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Replace all Ticket Number as Direct Link to the Ticket, let's say | |
var desc = "TKT-123,TKT-398,TKT-99 - dfklajflajfklajf".replace(/(TKT-\d+)+/gi,(match)=>{return '<a href="https://(website)/?ticket='+match+'" target=_blank>' + match + '</a>';}); | |
// Match all with spread them into array - you can avoid loop and .next() iteration! | |
let arr = [...str.matchAll(/TKT-\d+/gi)]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var data = { | |
"id":1, | |
"name":"Kiichi", | |
"dob":new Date() | |
}; | |
//{id: 1, name: "Kiichi", dob: Sat Dec 21 2019 16:45:45 GMT-0500 (Eastern Standard Time)} | |
// Spread operator is to useful to expand dictionary. | |
// To patch certain property, you can overwrite like below | |
var data2 = { | |
...data, | |
"name":"hello", | |
"dob":new Date() | |
}; | |
//{id: 1, name: "hello", dob: Sat Dec 21 2019 16:45:58 GMT-0500 (Eastern Standard Time)} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this is why switch should not be used | |
// can you explain why this syntax is valid ? | |
var val = 100; | |
switch(val){ | |
case 1: | |
console.log('one'); | |
case100: | |
console.log('a hundred'); | |
case 100: | |
defualt: | |
console.log('hey i thought i spelled default right but interpreter didnt complain this syntax.'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment