Skip to content

Instantly share code, notes, and snippets.

@rajaramtt
Created May 25, 2020 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajaramtt/d7c6f2f741e151ef72665d69cdff4625 to your computer and use it in GitHub Desktop.
Save rajaramtt/d7c6f2f741e151ef72665d69cdff4625 to your computer and use it in GitHub Desktop.
Refactoring Tips
const greet = (obj) => {
  return `${obj.greeting}, ${obj.firstName}${obj.lastName}`;
}
best way
const greet = ({
  greeting,
  firstName,
  lastName
}) => {
  return `${greeting}, ${firstName}${lastName}`;
}
const arr = [1, 2, 3].map(a => a * 2);
best way
const double = a => a * 2;
const arr = [1, 2, 3].map(double);
if (score === 100 ||
  remainingPlayers === 1 ||
  remainingPlayers === 0) {
  quitGame();
}
best way
const winnerExists = () => {
  return score === 100 ||
    remainingPlayers === 1 ||
    remainingPlayers === 0
}
if (winnerExists()) {
  quitGame();
}
const getValue = (prop) => {
  switch (prop) {
    case 'a': {
      return 1;
    }
    case 'b': {
      return 2;
    }
    case 'c': {
      return 3;
    }
  }
}
const val = getValue('a');
best way
const obj = {
  a: 1,
  b: 2,
  c: 3
}
const val = obj['a'];

OR

const map = new Map([['a', 1], ['b', 2], ['c', 3]])
const val = map.get('a')
Use Mobile First
How can you tell if you use mobile-first? If your media queries use min-width, you’re on the right track.
/* Mobile-first media query, everything above 600px will get the below styles */
@media (min-width: 600px) {
    /* your CSS rules */
}

/* Non mobile-first media query, everything below 600px will get the below styles */
@media (max-width: 600px) {
    /* your CSS rules */
}
if (fruit === 'apple' || fruit === 'orange' || fruit === 'grape') {
  //...
}

best way 

if (['apple', 'orange' ,'grape'].includes(fruit)) {
  //...
}

OR

if (['apple', 'orange', 'grape'].some(a => a === fruit)) {
  //...
}
Use Default Function Parameters and Destructuring
function test(fruit, quantity)
insed of 
function test(fruit, quantity = 1) { // if quantity not provided, default to one
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment