11
\$\begingroup\$

Just getting up to speed in Ramda, I have implemented this:

var R = require('ramda');
var divisibleBy = (b) => R.compose(R.equals(0), R.flip(R.modulo)(b))
var fizzbuzz =  R.map(R.cond([
  [R.both(divisibleBy(3), divisibleBy(5)), R.always('FizzBuzz')],
  [divisibleBy(3), R.always('Fizz')],
  [divisibleBy(5), R.always('Buzz')],
  [R.T, R.identity]
]));

console.log(fizzbuzz(R.range(1,101)))

Can I improve this, or is there a more canonical way of doing this in Ramda?

\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

This got some discussion in the Ramda Gitter Room. Although several people had different suggestions, my feeling -- and I believe the consensus -- was that this is very well done, and there's little to improve.

If you want it slightly more points-free, you could write divisibleBy like this:

var divisibleBy = R.curry(R.pipe(R.flip(R.modulo), R.equals(0)));

But, no, I don't think there is any more canonical way of doing this in Ramda.

BTW, I'm one of the original authors of Ramda, and as far as I've seen, yours is the very first Ramda fizzbuzz in existence!

\$\endgroup\$
2
  • \$\begingroup\$ in your suggestion, does it need the curry? \$\endgroup\$ Commented Oct 24, 2015 at 1:43
  • 1
    \$\begingroup\$ Yes, it does. We tried currying the result of pipe/compose in versions 0.16/0.17, but there were serious issues with it, and that's been reverted in version 0.18. \$\endgroup\$ Commented Oct 24, 2015 at 2:34
0
\$\begingroup\$

I won't claim it's more canonical but how about this for an alternative:

const isMultipleOf = curry(compose(equals(0),flip(modulo)));

const rule = (f, s) => when(
  compose(f, view(lensIndex(0))),
  over(lensIndex(1), concat(__,s))
);

const fizzBuzz = n => map(
  pipe(
    rule( isMultipleOf(3), 'Fizz' ),
    rule( isMultipleOf(5), 'Buzz' ),
    filter( compose(not, isEmpty) ),
    last
  ),
  xprod( times(inc, n), of('') )
);

const printFizzBuzz = compose( forEach(console.log), fizzBuzz );

printFizzBuzz(15);

It avoids the duplication of the 'FizzBuzz' case, i.e. when divisible by both 3 and 5.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.