Last active
November 20, 2015 20:08
-
-
Save dydx/d633abbf29decf35d66e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The goal here is to write fizzbuzz in such a | |
// way that adding new rules is as easy as defining | |
// a new predicate containing a number to check and | |
// return result. | |
// | |
// I want the changes to be easily made, in a single | |
// place, outside of the hard logic of the code | |
// | |
// I also want it so that there is no need for a special | |
// case for multiple predicates matching, e.g. `fizzbuzz` | |
// helper range function | |
function range(x) { | |
return Array.from(Array(x+1).keys()).slice(1, this.length); | |
} | |
// define a function that allows us to define predicates | |
function predicate (y, str) { | |
return function (x) { | |
if (x % y === 0) { | |
return str; | |
} | |
} | |
} | |
// list of predicates | |
var predicates = [ | |
function fizz (x) { | |
return predicate(3, 'fizz'); | |
}, | |
function buzz (x) { | |
return predicate(5, 'buzz'); | |
} | |
// adding new predicates is pretty simple, and doesn't affect the rest of the code | |
]; | |
// check each predicate against a given number | |
// building up a string of output | |
function check_predicates (x) { | |
return predicates.map(function (fn) { | |
return fn()(x); | |
}).filter(function (vals) { | |
return vals; | |
}).join(""); | |
} | |
function fizzbuzz(x) { | |
// if there was output from the predicate functions | |
// return that from the map, else return the number | |
return range(x).map(function (n) { | |
return (check_predicates(n) || n); | |
}) | |
} | |
// show what we've got | |
var output = fizzbuzz(35); | |
for(line of output) { | |
console.log(line); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment