DEV Community

Discussion on: Create pokedex with react hooks

Collapse
 
im6h profile image
Vu
export const COLOR: any = {
  fire: '#FD7D24',
  water: '#4592C4',
  grass: '#9BCC50',
  electric: '#EED535',
  dragon: '#4A446A',
  dark: '#707070',
  psychic: '#F366B9',
  ice: '#51C4E7',
  flying: '#649BD4',
  bug: '#729F3F',
  fairy: '#FDB9E9',
  ground: '#704326',
  normal: '#A4ACAF',
  rock: '#A38C21',
  fighting: '#D56723',
  poison: '#B97FC9',
  ghost: '#7B62A3',
  steel: '#84B7B8',
};

export const getColor = (type: any): string => {
  return COLOR[type] || COLOR.typeNormal;
}; 
Enter fullscreen mode Exit fullscreen mode

Use object literals instead of switch case and you have sort code.
This is example in my pokedex app.

Collapse
 
pes profile image
Pascual Hdez

Thanks for your comment, I agree with you, the object literals looks better on js code, but my intention with this tutorial is to guide developers that have less experience in javascript, so a switch case sentence might looks more natural for them, I think that I can do a second part of this tutorial and do some code refactoring in some places, and also apply redux and other technologies, thanks for the feedbak :)

Collapse
 
im6h profile image
Vu

No problem pro. Pokedex is my favorite app when I start begin new frontend Framework. Thanks for your post :) .

Collapse
 
robertnayael profile image
Robert Gulewicz

Btw, you can easily make it more type-safe:

const COLOR = {
  fire: '#FD7D24',
  water: '#4592C4',
  grass: '#9BCC50',
  electric: '#EED535',
  dragon: '#4A446A',
  dark: '#707070',
  psychic: '#F366B9',
  ice: '#51C4E7',
  flying: '#649BD4',
  bug: '#729F3F',
  fairy: '#FDB9E9',
  ground: '#704326',
  normal: '#A4ACAF',
  rock: '#A38C21',
  fighting: '#D56723',
  poison: '#B97FC9',
  ghost: '#7B62A3',
  steel: '#84B7B8',
};

export const getColor = (type: keyof typeof COLOR): string => {
  return COLOR[type] || COLOR.normal;
}; 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
qnemes profile image
Vladyslav

You can do even better, just use enums:

export enum elementColor {
  bug = '#729f3f',
  dragon = '#53a4cf',
  fairy = '#fdb9e9',
  fire = '#fd7d24',
  ghost = '#7b62a3',
  ground = '#f7de3f',
  normal = '#a4acaf',
  pyschic = '#f366b9',
  dark = '#707070',
  electric = '#eed535',
  fighting = '#d56723',
  flying = '#3dc7ef',
  grass = '#9bcc50',
  ice = '#51c4e7',
  poison = '#b97fc9',
  psychic = '#792359',
  rock = '#a38c21',
  steel = '#9AA899',
  water = '#4592c4',
};
Enter fullscreen mode Exit fullscreen mode

Then, just access it:

elementColor[type.name]
Enter fullscreen mode Exit fullscreen mode