In this article, I compile some of the JavaScript “techniques” that I usually use in my day-to-day life, saving a lot of time. I hope you find them useful!
Let’s imagine that we want to develop a generic function, given some parameters and a function. This function is executed then with these parameters.
For example, a calculator with N parameters and N operations. You can easily achieve this using the spread operator and the reduce function:
function calculator(operation, ...numbers) {
return operation(...numbers);
}
function add(...numbers) {
return numbers.reduce( (total, num) => total + num, 0);
}
function subtract(...numbers) {
return numbers.reduce( (total, num) => total - num, 0);
}
function multiply(...numbers) {
return numbers.reduce( (total, num) => total * num, 1);
}
console.log(calculator(add, 1, 2, 3, 4, 5));
console.log(calculator(subtract, 10, 2, 1));
console.log(calculator(multiply, 2, 2, 2, 2));
Different operations with our generic function
Sometimes you would probably have found useful to use ranges in a Switch sentence. Here is an example of how to do it:
function chooseSportByTemperature(fahrenheit) {
let sport;
switch (true) {
case (fahrenheit >= 15 && fahrenheit <=20):
sport = 'Running';
break;
case (fahrenheit > 20 && fahrenheit <= 30):
sport = 'Cycling';
break;
case (fahrenheit > 30):
sport = 'Stay in home';
break;
default:
sport = 'Sex';
}
return sport;
}
A clean way to group case sentences:
function setMyValueByValue(value) {
let myValue;
switch (value)
{
case "value1":
case "value2":
case "value3":
myValue = "My value 1-2-3"
break;
case "value4":
myValue = "My value 4"
break;
default:
myValue = "Default value"
}
return myValue;
}
console.log(setMyValueByValue("value1"));
console.log(setMyValueByValue("value2"));
console.log(setMyValueByValue("value3"));
console.log(setMyValueByValue("value4"));
console.log(setMyValueByValue("value5"));
Grouping multiple switch cases.
It is possible to wait to await the completion of multiple asynchronous functions using (Promise.all) inside the async function.
function resolveAfter1Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 1000);
});
}
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
function resolveAfter3Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 3000);
});
}
function resolveAfter4Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 4000);
});
}
async function asyncFunction() {
console.log('start');
const result = await Promise.all(
[resolveAfter1Seconds(),
resolveAfter2Seconds(),
resolveAfter3Seconds(),
resolveAfter4Seconds()])
console.log(result); //resolved after 10 seconds !
console.log('end');
}
asyncFunction();
#javascript #programming #developer #web-development