Created
October 1, 2012 18:54
-
-
Save kos59125/3813702 to your computer and use it in GitHub Desktop.
FizzBuzz in TypeScript
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
module FizzBuzz | |
{ | |
var convert = function (fb : FizzBuzz, n : number) : string | |
{ | |
var buffer = "" | |
for (var current = fb; current != null; current = current.next) | |
{ | |
buffer = current.consume (n, buffer) | |
} | |
if (buffer.length == 0) | |
{ | |
buffer = n.toString () | |
} | |
return buffer | |
} | |
export var doFizzzBuzz = function (n : number) | |
{ | |
var fb = new Fizz (new Buzz (null)) | |
var table = document.createElement ("table") | |
document.body.appendChild (table) | |
for (var i = 1; i <= n; i++) | |
{ | |
var row = document.createElement ("tr") | |
var key = document.createElement ("th") | |
key.appendChild (document.createTextNode (i.toString ())) | |
var value = document.createElement ("td") | |
value.appendChild (document.createTextNode (convert (fb, i))) | |
row.appendChild (key) | |
row.appendChild (value) | |
table.appendChild (row) | |
} | |
} | |
class FizzBuzz | |
{ | |
next : FizzBuzz; | |
consume : (n : number, buffer : string) => string; | |
constructor (fb : FizzBuzz) | |
{ | |
this.next = fb | |
} | |
} | |
class Fizz extends FizzBuzz | |
{ | |
constructor (fb : FizzBuzz) | |
{ | |
super (fb) | |
} | |
consume = function (n : number, buffer : string) : string | |
{ | |
if (n % 3 == 0) | |
{ | |
return buffer + "Fizz" | |
} | |
else | |
{ | |
return buffer | |
} | |
} | |
} | |
class Buzz extends FizzBuzz | |
{ | |
constructor (fb : FizzBuzz) | |
{ | |
super (fb) | |
} | |
consume = function (n : number, buffer : string) : string | |
{ | |
if (n % 5 == 0) | |
{ | |
return buffer + "Buzz" | |
} | |
else | |
{ | |
return buffer | |
} | |
} | |
} | |
} | |
FizzBuzz.doFizzzBuzz (100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment