Skip to content

Code Refactoring

Biswajit Sundara edited this page May 1, 2023 · 2 revisions

1. Alternative Of Switch

  • We can make use of objects instead of switch and achieve the same result.
  • Object will look more cleaner and easy to maintain however please note switch case is the best in terms of performance.
function getCurrency(country) {
    var currency = {
        'India': 'Rupee',
        'United States': 'Dollar',
        'Europe': 'Euro',
        'default': 'Invalid Choice'
    };
    return (currency[country] || currency['default']);
}

let currency = getCurrency('India');
console.log(currency);

2. Correct way to usage Async await.

  • Use waterfall structure when the methods are dependent on each other
const data = await getData();
await processData(data);
  • Use Parallel approach if the methods are independent.
Promise.all([p1, p2, p3]).then((values) => {
  console.log(values); 
});

Check the promise.all settled also.

3. Deep Nesting

Avoid nesting more than 3 levels.

  • Use inversion technique
  • Use return statements
  • Break down the code into smaller functions.

4. File Management

Keep the content that's not related to the code in separate files

  • For example proxy's, environment configuration etc.

Clone this wiki locally