small medium large xlarge

Posts by David Phillips

Generic-user-small
05 Jun 2015, 22:54
David Phillips (1 post)
(from Programming Elixir > Exercise: ListsAndRecursion-8)

Mine’s a little screwy, but I like it

#!/usr/bin/env elixir

defmodule TaxAndOrders do
  def total(orders,tax) do
    Enum.map(orders, 
      fn [a,b={:ship_to, state},c={:net_amount, n}] -> # Deconstruct list and pull out the state and order amount
        # Pull out the states in the tax list and check if current state is in there
        if state in (for {st, _rate} <- tax do st end) do 
          [a,b,c, total_amount: n+(n*tax[state])] # If it is, apply the appropriate tax rate
        else
          [a,b,c, total_amount: n] # If not just have the total_amount equal the net_amount
        end
      end)       
  end
end


tax_rates = [ NC: 0.075, TX: 0.08 ]
orders = [
    [ id: 123, ship_to: :NC, net_amount: 100.00 ],
    [ id: 124, ship_to: :OK, net_amount:  35.50 ],
    [ id: 125, ship_to: :TX, net_amount:  24.00 ],
    [ id: 126, ship_to: :TX, net_amount:  44.80 ],
    [ id: 127, ship_to: :NC, net_amount:  25.00 ],
    [ id: 128, ship_to: :MA, net_amount:  10.00 ],
    [ id: 129, ship_to: :CA, net_amount: 102.00 ],
    [ id: 120, ship_to: :NC, net_amount:  50.00 ] ]

orders |> TaxAndOrders.total(tax_rates) |> IO.inspect

1 post