Advertisement
mituri

[JS] object instead of switch

Apr 23rd, 2022
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. INSTEAD THIS :
  2.  
  3.  
  4. function getTranslation(rhyme) {
  5. switch (rhyme.toLowerCase()) {
  6. case "apples and pears":
  7. return "Stairs";
  8. case "hampstead heath":
  9. return "Teeth";
  10. case "loaf of bread":
  11. return "Head";
  12. case "pork pies":
  13. return "Lies";
  14. case "whistle and flute":
  15. return "Suit";
  16. default:
  17. return "Rhyme not found";
  18. }
  19. }
  20.  
  21. U CAN USE THIS
  22.  
  23.  
  24. function getTranslationMap(rhyme) {
  25. const rhymes = {
  26. "apples and pears": "Stairs",
  27. "hampstead heath": "Teeth",
  28. "loaf of bread": "Head",
  29. "pork pies": "Lies",
  30. "whistle and flute": "Suit",
  31. };
  32.  
  33. return rhymes[rhyme.toLowerCase()] ?? "Rhyme not found";
  34. }
  35.  
  36.  
  37. ----------- EXAMPLE WITH FUNCTIONS INSIDE ------
  38.  
  39. function calculate(num1, num2, action) {
  40. const actions = {
  41. add: (a, b) => a + b,
  42. subtract: (a, b) => a - b,
  43. multiply: (a, b) => a * b,
  44. divide: (a, b) => a / b,
  45. };
  46.  
  47. return actions[action]?.(num1, num2) ?? "Calculation is not recognised";
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement