Skip to content

Instantly share code, notes, and snippets.

@mdarby
Created September 21, 2014 04:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdarby/1acc75cbc2d23d6c97b5 to your computer and use it in GitHub Desktop.
Save mdarby/1acc75cbc2d23d6c97b5 to your computer and use it in GitHub Desktop.
POST to localhost:8080/change with {given: 1000, owed: 450} and receive a JSON response of the change due in standard US currency. Some DRYing should occur around the Denominations.
package main
import (
"encoding/json"
"io"
"log"
"net/http"
"strconv"
)
type Denomination struct {
Name string
Value int
Count int
}
type Change struct {
Given int
Owed int
_Left int
Denominations []*Denomination
}
func (c *Change) Deduct(d *Denomination) {
flag := true
for flag {
if c._Left >= d.Value {
c._Left -= d.Value
d.Count += 1
} else {
flag = false
}
}
}
func (c *Change) ToJSON() ([]byte, error) {
data := make(map[string]int)
for i := 0; i < len(c.Denominations); i++ {
d := c.Denominations[i]
if d.Count > 0 {
data[d.Name] = d.Count
}
}
return json.Marshal(data)
}
func (c *Change) InitDenominations() {
c.Denominations = append(c.Denominations, &Denomination{Name: "Hundred", Value: 10000, Count: 0})
c.Denominations = append(c.Denominations, &Denomination{Name: "Fifty", Value: 5000, Count: 0})
c.Denominations = append(c.Denominations, &Denomination{Name: "Twenty", Value: 2000, Count: 0})
c.Denominations = append(c.Denominations, &Denomination{Name: "Ten", Value: 1000, Count: 0})
c.Denominations = append(c.Denominations, &Denomination{Name: "Five", Value: 500, Count: 0})
c.Denominations = append(c.Denominations, &Denomination{Name: "One", Value: 100, Count: 0})
c.Denominations = append(c.Denominations, &Denomination{Name: "Quarter", Value: 25, Count: 0})
c.Denominations = append(c.Denominations, &Denomination{Name: "Dime", Value: 10, Count: 0})
c.Denominations = append(c.Denominations, &Denomination{Name: "Nickel", Value: 5, Count: 0})
c.Denominations = append(c.Denominations, &Denomination{Name: "Penny", Value: 1, Count: 0})
}
func MakeChange(Given int, Owed int) *Change {
c := &Change{Given: Given, Owed: Owed}
c.InitDenominations()
c._Left = c.Given - c.Owed
for i := 0; i < len(c.Denominations); i++ {
c.Deduct(c.Denominations[i])
}
return c
}
func changeHandler(w http.ResponseWriter, r *http.Request) {
given, _ := strconv.Atoi(r.FormValue("given"))
owed, _ := strconv.Atoi(r.FormValue("owed"))
json, _ := MakeChange(given, owed).ToJSON()
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, string(json))
}
func main() {
http.HandleFunc("/change", changeHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
@mdarby
Copy link
Author

mdarby commented Sep 21, 2014

I need to DRY the areas around Denomination along with add more proper error handling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment