Rewriting switch statements to lookup objects
JavaScriptAll snippets in this category →
Posted on Some switch-statements can be replaced with lookup-tables in JavaScript. If every case
immediately returns a value, this pattern achieves the same in fewer lines of code.
// before: switching through the values to return a number requires a lot of code
const getFeetForAnimal = animal => {
switch (animal) {
case "bird":
return 2
case "dog":
return 4
case "fish":
return 0
case "spider":
return 8
}
}
// after: a lookup object and implicit `return` do the same in fewer lines
const getFeetForAnimal = animal => ({
bird: 2,
dog: 4,
fish: 0,
spider: 8
})[animal]
getFeetForAnimal("dog") // ⇒ 4
getFeetForAnimal("gorilla") // ⇒ undefined (does not exist in lookup table)
// before: switching through the values to return a number requires a lot of code
const getFeetForAnimal = animal => {
switch (animal) {
case "bird":
return 2
case "dog":
return 4
case "fish":
return 0
case "spider":
return 8
}
}
// after: a lookup object and implicit `return` do the same in fewer lines
const getFeetForAnimal = animal => ({
bird: 2,
dog: 4,
fish: 0,
spider: 8
})[animal]
getFeetForAnimal("dog") // ⇒ 4
getFeetForAnimal("gorilla") // ⇒ undefined (does not exist in lookup table)
// before: switching through the values to return a number requires a lot of code
const getFeetForAnimal = animal => {
switch (animal) {
case "bird":
return 2
case "dog":
return 4
case "fish":
return 0
case "spider":
return 8
}
}
// after: a lookup object and implicit `return` do the same in fewer lines
const getFeetForAnimal = animal => ({
bird: 2,
dog: 4,
fish: 0,
spider: 8
})[animal]
getFeetForAnimal("dog") // ⇒ 4
getFeetForAnimal("gorilla") // ⇒ undefined (does not exist in lookup table)
// before: switching through the values to return a number requires a lot of code
const getFeetForAnimal = animal => {
switch (animal) {
case "bird":
return 2
case "dog":
return 4
case "fish":
return 0
case "spider":
return 8
}
}
// after: a lookup object and implicit `return` do the same in fewer lines
const getFeetForAnimal = animal => ({
bird: 2,
dog: 4,
fish: 0,
spider: 8
})[animal]
getFeetForAnimal("dog") // ⇒ 4
getFeetForAnimal("gorilla") // ⇒ undefined (does not exist in lookup table)