From ada2c83548c0c08f39e8ffee1bdd6eedc100cdc8 Mon Sep 17 00:00:00 2001 From: Andinus Date: Sun, 5 Sep 2021 22:20:04 +0530 Subject: 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. --- javascript/raindrops/raindrops.js | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'javascript') 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; }; -- cgit 1.4.1-2-gfad0