Skip to content

Instantly share code, notes, and snippets.

@TSFoster
Created July 2, 2013 14:38
Show Gist options
  • Save TSFoster/5909850 to your computer and use it in GitHub Desktop.
Save TSFoster/5909850 to your computer and use it in GitHub Desktop.
Tiny command line utility that lets you work out values for tax or before- or after-tax earnings. `tax earnings_from x` lets you know your after-tax earnings from your before-tax earnings. `tax tax_on x` lets you know how much you'll be taxed from your before-tax earnings. `tax to_earn x` lets you know how much you'll have to earn to end up with…
#!/usr/bin/env ruby
# encoding: utf-8
class TaxCalculator
INFINITY = 1.0/0.0
DEFAULT_RATES = {
0.0...9440.0 => 0.0 ,
9440.0...32010.0 => 0.2 ,
32010.0...150000.0 => 0.4 ,
150000.0..INFINITY => 0.45
}
def initialize rates=nil
@rates = rates || DEFAULT_RATES
end
def earnings_from amount
amount - tax_on(amount)
end
def tax_on amount
@rates.inject(0.0) do |sum, (range, rate)|
amount > range.first ? ([amount, range.last].min - range.first)*rate + sum : sum
end
end
def to_earn amount
@rates.sort{|(a,_),(b,_)|a.first<=>b.first}.reverse.each do |range, rate|
e = earnings_from range.first
return range.first + (amount-e)/(1-rate) if e < amount
end
end
def to_be_taxed amount
@rates.sort{|(a,_),(b,_)|a.first<=>b.first}.reverse.each do |range, rate|
e = tax_on range.first
return range.first + (amount-e)/rate if e < amount
end
end
end
tax_calculator = TaxCalculator.new
command = ARGV[1] ? ARGV[0] : ARGV[0] ? 'tax_on' : nil
amount = ARGV[1] ? ARGV[1] : ARGV[0] ? ARGV[0] : nil
if ['earnings_from', 'tax_on', 'to_earn', 'to_be_taxed'].include? command
puts "£%.2f" % tax_calculator.send(command, amount.to_f)
else
puts "USAGE tax [earnings_from|tax_on|to_earn|to_be_taxed] amount"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment