Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Tax Calculation Challenge in CoffeeScript
class TaxSlice
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
calculate: (amount) ->
if (amount == 0 or amount < @min)
return 0
if @max is null
taxedAmount = amount - @min
taxedAmount = if amount > @max then @max - @min else amount - @min
return Number (taxedAmount * @rate).toFixed(2)
class TaxCalculator
constructor: ->
@taxSlices = new Array
addTaxSlice: (min, max, rate) ->
slice = new TaxSlice min, max, rate
@taxSlices.push slice "Added tax slice #{min} #{max} #{rate}"
calculateTax: (amount) -> "Number of tax slices is #{@taxSlices.length}"
taxes = 0; count = 0
for slice in @taxSlices
tax = slice.calculate amount
taxes += tax; count++ "Tax #{count} is #{tax}"
return taxes
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
# Run application
app = new App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.