| 3 | 3 | // convenience to get you started writing code faster. |
| 4 | 4 | // |
| 5 | 5 | |
| 6 | | export const sum = () => { |
| 7 | | throw new Error('Remove this line and implement the function'); |
| 6 | export const sum = (magicalItems, level) => { |
| 7 | // Edge Case: Level is 0 or 1, no multiples possible |
| 8 | if (level <= 1) { |
| 9 | return 0; |
| 10 | } |
| 11 | |
| 12 | // Edge Case: Empty list of magical items |
| 13 | if (!magicalItems || magicalItems.length === 0) { |
| 14 | return 0; |
| 15 | } |
| 16 | |
| 17 | const multiples = new Set(); |
| 18 | |
| 19 | // For each magical item base value |
| 20 | for (const baseValue of magicalItems) { |
| 21 | // Edge Case: Negative or zero base value |
| 22 | if (baseValue <= 0) { |
| 23 | continue; |
| 24 | } |
| 25 | |
| 26 | // Edge Case: Base value greater than or equal to level number |
| 27 | if (baseValue >= level) { |
| 28 | continue; |
| 29 | } |
| 30 | |
| 31 | // Find all multiples of baseValue less than level |
| 32 | for (let multiple = baseValue; multiple < level; multiple += baseValue) { |
| 33 | multiples.add(multiple); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | // Sum all unique multiples |
| 38 | let sum = 0; |
| 39 | for (const multiple of multiples) { |
| 40 | sum += multiple; |
| 41 | } |
| 42 | |
| 43 | return sum; |
| 8 | 44 | }; |
| 45 | |
| 46 | // Handled Edge Cases: Level is 0 or 1, empty list of magical items, negative or zero base values, base values greater than or equal to level number |