Skip to content

Instantly share code, notes, and snippets.

@kos59125
Created October 1, 2012 18:54
Show Gist options
  • Save kos59125/3813702 to your computer and use it in GitHub Desktop.
Save kos59125/3813702 to your computer and use it in GitHub Desktop.
FizzBuzz in TypeScript
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