Skip to content

Instantly share code, notes, and snippets.

@EdisonChendi
Last active August 29, 2015 14:26
Show Gist options
  • Save EdisonChendi/1e62659640c45e81e886 to your computer and use it in GitHub Desktop.
Save EdisonChendi/1e62659640c45e81e886 to your computer and use it in GitHub Desktop.
try some functional js on FizzBuzz...
/*
* rely on underscore
*/
// ============ imperative ============
function fizzbuzz(arr) {
var i = 0,
len = arr.length,
curr = null;
for (; i < len; i++) {
curr = arr[i];
if (curr % 15 === 0) {
console.log(curr, "fizzbuzz");
} else if (curr % 3 === 0) {
console.log(curr, "fizz");
} else if (curr % 5 === 0) {
console.log(curr, "buzz");
}
}
}
// fizzbuzz(_.range(100));
// ============ functional ============
function log(str) {
return function() {
console.log(str);
};
}
function divisibleBy(n) {
return function(x) {
return x % n === 0;
};
}
function existy(x) {
return x != undefined;
}
function truthy(x) {
return x !== false && existy(x);
}
function doWhen(pred, action) {
return function() {
if (truthy(pred.apply(this, arguments))) {
return action();
}
};
}
function construct(arr, ele) {
return _.toArray(arr).concat([ele]);
}
function curryRight(fn) {
return function(right) {
return function() {
fn.apply(null, construct(arguments, right));
};
};
}
/*
// wrong implementaion
var doFizzBuzz = function(ele) {
doWhen(divisibleBy(15), log("fizzbuzz"))(ele);
doWhen(divisibleBy(3), log("fizz"))(ele);
doWhen(divisibleBy(5), log("buzz"))(ele);
};
var functionalFizzBuzz = curryRight(_.each)(doFizzBuzz);
functionalFizzBuzz(_.range(100));
*/
// ============ let's get fancy! ===============
var doUntil = function(fnArr, stopCondition) {
var len = fnArr.length;
return function(obj) {
var index = 0,
result = null;
for (; index < len; index++) {
result = fnArr[index](obj);
if (result === stopCondition(result)) {
return result;
}
}
}
};
function always(val) {
return function() {
return val;
};
}
var alwaysTrue = always(true);
var when = function when(pred) {
when.do = function (action) {
return function(obj) {
var judge = pred(obj);
if(judge) {
action();
}
return judge;
}
};
return when;
};
var doFancyFunctionalFizzBuzz = doUntil(
[
when(divisibleBy(15)).do(log("fizzbuzz")),
when(divisibleBy(3)).do(log("fizz")),
when(divisibleBy(5)).do(log("buzz"))
],
alwaysTrue
);
var fancyFunctionalFizzBuzz = curryRight(_.each)(doFancyFunctionalFizzBuzz);
fancyFunctionalFizzBuzz(_.range(100));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment