Last Updated: February 25, 2016
·
2.396K
· chrisbumgardner

How to use pattern matching to solve FizzBuzz in Javascript with Node.js & Funcy

I was inspired to write a FizzBuzz solution this morning using functional pattern matching in Javascript after seeing this Clojure example https://github.com/clojure/core.match#example-usage. A little searching turned up this awesome npm module for Node.js named Funcy: https://github.com/bramstein/funcy. Here's how I implemented FizzBuzz with it:

var fun = require('funcy')
  , _ = fun.wildcard
  , n;
for (n = 1; n <= 100; n++) {
  console.log(
    fun(
      [[0, 0], function() { return 'FizzBuzz'; }],
      [[0, _], function() { return 'Fizz'; }],
      [[_, 0], function() { return 'Buzz'; }],
      [_, function() { return n; }]
    )([n % 3, n % 5])
  );
}

Or see gist here: https://gist.github.com/4298666

1 Response
Add your response

Nice! Looks almost the same in Erlang

fizzbuzz(N) ->
  [fizz_or_buzz(X) || X <- lists:seq(1, N)].
fizz_or_buzz(X) ->
  case {X rem 3, X rem 5} of
    {0, 0} -> fizzbuzz;
    {0, _} -> fizz;
    {_, 0} -> buzz;
    {_, _} -> X
  end.
over 1 year ago ·