diff options
author | Andinus <andinus@nand.sh> | 2021-09-05 22:20:04 +0530 |
---|---|---|
committer | Andinus <andinus@nand.sh> | 2021-09-05 22:20:04 +0530 |
commit | ada2c83548c0c08f39e8ffee1bdd6eedc100cdc8 (patch) | |
tree | 5ec3f9d1c00f7048a3048678fba56bcc2ecf39d8 /javascript/raindrops | |
parent | b05021bb9ca6bc6f5189bfe8f2cf15e0a78fdb5e (diff) | |
download | exercism-ada2c83548c0c08f39e8ffee1bdd6eedc100cdc8.tar.gz |
JS: Raindrops: Switch to using a map
I switched to single object literals initially: const factorToSound = { 3: "Pling", 5: "Plang", 7: "Plong" }; and used `for .. if` to iterate over them, that may cause some issues: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of#difference_between_for...of_and_for...in I decided to switch to using Maps and iterate over them with `for .. of` instead.
Diffstat (limited to 'javascript/raindrops')
-rw-r--r-- | javascript/raindrops/raindrops.js | 18 |
1 files changed, 9 insertions, 9 deletions
diff --git a/javascript/raindrops/raindrops.js b/javascript/raindrops/raindrops.js index c7614d5..4a39ec9 100644 --- a/javascript/raindrops/raindrops.js +++ b/javascript/raindrops/raindrops.js @@ -1,19 +1,19 @@ 'use strict'; export const convert = (number) => { - const rules = [ - {factor: 3, result: 'Pling'}, - {factor: 5, result: 'Plang'}, - {factor: 7, result: 'Plong'} - ]; + const factorToSound = new Map([ + [3, 'Pling'], + [5, 'Plang'], + [7, 'Plong'] + ]); let drops = ""; - rules.forEach(drop => { - if (number % drop.factor === 0) - drops += drop.result; - }); + for (const [factor, sound] of factorToSound) + if (number % factor === 0) + drops += sound; if (drops === "") drops += number; + return drops; }; |