Skip to content

Instantly share code, notes, and snippets.

@wahidshalaly
Created October 15, 2011 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wahidshalaly/1289852 to your computer and use it in GitHub Desktop.
Save wahidshalaly/1289852 to your computer and use it in GitHub Desktop.
Tax Calculation Challenge in CoffeeScript
#---BEGIN---
class TaxSlice
#---BEGIN---
constructor: (min, max, rate) ->
if min is null
throw new Error "null value is not acceptable for min"
if min >= max and max is not null
throw new Error "min cannot be greater than or equal max"
if rate < 0
throw new Error "positive tax rate is required."
@min = min
@max = max
@rate = rate
#---END---
#---BEGIN---
calculate: (amount) ->
if (amount == 0 or amount < @min)
return 0
if @max is null
taxedAmount = amount - @min
else
taxedAmount = if amount > @max then @max - @min else amount - @min
return Number (taxedAmount * @rate).toFixed(2)
#---END---
#---END---
#---BEGIN---
class TaxCalculator
constructor: ->
@taxSlices = new Array
#---BEGIN---
addTaxSlice: (min, max, rate) ->
slice = new TaxSlice min, max, rate
@taxSlices.push slice
console.info "Added tax slice #{min} #{max} #{rate}"
#---END---
#---BEGIN---
calculateTax: (amount) ->
console.info "Number of tax slices is #{@taxSlices.length}"
taxes = 0; count = 0
for slice in @taxSlices
tax = slice.calculate amount
taxes += tax; count++
console.info "Tax #{count} is #{tax}"
return taxes
#---END---
#---END---
#---BEGIN---
class App
main: ->
calc = new TaxCalculator
calc.addTaxSlice 0, 5070, 0.10
calc.addTaxSlice 5071, 8660, 0.14
calc.addTaxSlice 8661, 14070, 0.23
calc.addTaxSlice 14071, 212410, 0.30
calc.addTaxSlice 212411, 40230, 0.33
calc.addTaxSlice 40231, null, 0.45
taxes = calc.calculateTax 5800
alert "Taxes: " + taxes
#---END---
# Run application
app = new App
app.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment