Last active
December 20, 2015 20:28
-
-
Save hitsujiwool/6190403 to your computer and use it in GitHub Desktop.
JavaScript implementation of http://codeiq.hatenablog.com/entry/2013/08/07/162935
This file contains hidden or 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
function App() { | |
this.specAndMessages = []; | |
}; | |
App.prototype.addSpecAndMessage = function(spec, message) { | |
this.specAndMessages.push({ | |
spec: spec, | |
message: message | |
}); | |
}; | |
App.prototype.run = function(until) { | |
for (var i = 0; i < until; i++) { | |
console.log(this.checkSpecAndGetMessage(i + 1)); | |
} | |
}; | |
App.prototype.checkSpecAndGetMessage = function(n) { | |
var spec, | |
message; | |
for (var i = 0, len = this.specAndMessages.length; i < len; i++) { | |
if (this.specAndMessages[i].spec.isSatisfiedBy(n)) { | |
return this.specAndMessages[i].message; | |
} | |
} | |
return n; | |
}; | |
function Spec(divisor) { | |
this.divisor = divisor; | |
}; | |
Spec.prototype.isSatisfiedBy = function(n) { | |
return n % this.divisor === 0; | |
}; | |
module.exports = { | |
App: App, | |
Spec: Spec | |
}; |
This file contains hidden or 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
var fizzBuzz = require('./fizz_buzz'), | |
app = new fizzBuzz.App(); | |
app.addSpecAndMessage(new fizzBuzz.Spec(15), 'fizzbuzz'); | |
app.addSpecAndMessage(new fizzBuzz.Spec(3), 'fizz'); | |
app.addSpecAndMessage(new fizzBuzz.Spec(5), 'buzz'); | |
app.run(30); |
This file contains hidden or 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
function fizzBuzz(n) { | |
for (var i = 1; i <= n; i++) { | |
if (i % 15 === 0) { | |
console.log('fizzbuzz'); | |
} else if (i % 3 === 0) { | |
console.log('fizz'); | |
} else if (i % 5 === 0) { | |
console.log('buzz'); | |
} else { | |
console.log(i); | |
} | |
} | |
} | |
fizzBuzz(30); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment