Skip to content

Instantly share code, notes, and snippets.

@TSFoster
Created July 2, 2013 14:38
Show Gist options
  • Select an option

  • Save TSFoster/5909850 to your computer and use it in GitHub Desktop.

Select an option

Save TSFoster/5909850 to your computer and use it in GitHub Desktop.

Revisions

  1. TSFoster revised this gist Jul 2, 2013. No changes.
  2. TSFoster created this gist Jul 2, 2013.
    51 changes: 51 additions & 0 deletions tax
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    #!/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