How do you quickly resolve who owes whom what money when a group of people eat together at a restaurant and one person pays at the end?
Answering this question is small, well defined little programming challenge and here’s the approach I took this time.
I know I wanted some data model to capture 3 things:
- what the item is
- how much it cost
- who should be associated with that cost
- This will capture the “this group of people split this one thing” and every variation of that
Once I’ve gone through and annotated the receipt, then I want some group of functions to take a sequence of this data model and derive every other fact on the receipt. Heck, you could even derive other facts implied by the receipt, like the alcohol tax rate, for example.
I’ll walk through my initial attempt here, but I think it would be more interesting to follow this up as a local clojurescript webapp that will do this live.
(defn split-shared
[groups]
(let [num-people (count (dissoc groups :all))
shared-total (->> groups
:all
(mapv second)
(reduce +))
shared-things (mapv first
(:all groups))
shared-cost (/ shared-total
num-people
#_1.0)
shared-line-item (conj shared-things
shared-cost)]
(->> (dissoc groups :all)
(reduce (fn [acc [person things]]
(assoc acc
person
(conj things
shared-line-item)))
{}))))
(defn divide-split-items
[items]
(reduce (fn [acc [item cost & people]]
(reduce (fn [acc2 person]
(update acc2
person
(fnil conj [])
[item (/ cost
(count people))]))
acc
people))
{}
items))
(defn group-subtotal
[{:keys [subtotal] :as _meal}
groups]
(->> groups
(reduce (fn [acc [person things]]
(assoc acc
person
{:items things
:subtotal (->> things
(mapv second)
(reduce +))}))
{})))
(defn round-cents
[amt]
(->> amt
(format "%.2f")
parse-double))
(defn split-amount
[label amount total groups]
(->> groups
(reduce (fn [acc [person {person-total :subtotal}]]
(update acc
person
assoc
label
(* amount
(/ person-total
total))))
groups)))
(defn apply-taxes-and-fees
[meal groups]
(reduce (fn [acc [label amount]]
(split-amount label amount
(:subtotal meal)
acc))
groups
(select-keys meal
[:surcharge :tax :tip])))
(defn group-total
[groups]
(->> groups
(reduce (fn [acc [person {:keys [subtotal surcharge tax tip]}]]
(update acc
person
assoc
:total
(+ subtotal
surcharge
tax
tip)))
groups)))
(defn sum-by-key
[k coll]
(->> coll
vals
(mapv k)
(reduce +)))
