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
Written by Chris Bumgardner
Related protips
1 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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Nodejs
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#