-
Notifications
You must be signed in to change notification settings - Fork 118
/
general-fizzbuzz.js
50 lines (46 loc) · 1.26 KB
/
general-fizzbuzz.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Write a generalized version of FizzBuzz that works for any list
// of factors, along with their words. This is basically a "fizzbuzz"
// implementation where the rules of the game are supplied to the user.
// Create a function to implement this. The function should take two parameters.
// The first will be an array with the FizzBuzz rules.
// For example: [ [3,"Fizz"] , [5,"Buzz"] ].
// This indcates that Fizz should be printed if the number is a multiple of 3
// and Buzz if it is a multiple of 5. If it is a multiple of both then
// the strings should be concatenated in the order specified in the array.
// In this case, FizzBuzz if the number is a multiple of 3 and 5.
// The second parameter is the number for which the function should
// return a string as stated above.
function genFizzBuzz (rules, num) {
const numbers = Array.from({ length: num }, (e, i) => i + 1);
return numbers.map(item => {
return rules.reduce((str, rule) => {
if (item % rule[0] === 0) str += rule[1];
return str;
}, '') || item;
}).join('\n');
}
console.log(genFizzBuzz([
[3, 'Fizz'],
[5, 'Buzz'],
[7, 'Baxx']
], 20));
// 1
// 2
// Fizz
// 4
// Buzz
// Fizz
// Baxx
// 8
// Fizz
// Buzz
// 11
// Fizz
// 13
// Baxx
// FizzBuzz
// 16
// 17
// Fizz
// 19
// Buzz