Parameter name (number, fizz) => number % fizz === 0
The fizz
isn't very indicative of what it represents. Consider divisor
or possibleDivisor
instead.
Avoid reassignment in functional programming: your ++currentIndex
reassigns that variable. If you needed recursion, pass the variable plus one instead of incrementing the variable and passing it: use currentIndex + 1
.
Move required side-effects to the edges of the script, since you want a functional approach - make the fizzBuzz
function functional by having it return a string which can be logged by the caller, instead of fizzBuzz
itself log the results. (console.log
is a side-effect, so including it in a function makes it non-functional)
getSubstitutes
recursion? The recursive approach used in getSubstitutes
, while it works, seems a bit off to me. Functional programming excels at pure transformation of data (and in JavaScript, with object/array methods), and given the substitutes
array, I think a .filter
/ .map
would be a bit more appropriate, without any recursion.
fizzBuzz
recursion too? - if you feel like it, you can create an array of the values to be logged all at once by using Array.from
instead of the somewhat imperative approach of incrementing and testing currentIndex
:
const isDivisible = (number, divisor) => number % divisor === 0;
const getSubstitutes = (number, substitutes) => substitutes
.filter(({ divisor }) => isDivisible(number, divisor))
.map(({ substitute }) => substitute)
.join('');
const fizzBuzz = (length, substitutes) => (
Array.from(
{ length },
(_, i) => getSubstitutes(i + 1, substitutes) || i + 1
)
.join('\n')
);
const substitutes = [
{
divisor: 3,
substitute: "fizz",
},
{
divisor: 5,
substitute: "buzz",
},
];
console.log(fizzBuzz(100, substitutes));
Recursion is useful in functional programming when you need persistent state (like with a game, or memoization), but it can make the logic somewhat difficult to understand at a glance - I'd only use it when other approaches don't work well, or when the recursive logic to implement is natural (like with a factorial).