Skip to content

Instantly share code, notes, and snippets.

@codemodify
Created June 26, 2019 19:27
Show Gist options
  • Save codemodify/674141fcd9d561d02bb4cb98bbcc51a3 to your computer and use it in GitHub Desktop.
Save codemodify/674141fcd9d561d02bb4cb98bbcc51a3 to your computer and use it in GitHub Desktop.
the-pizza-fun
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"sort"
)
type Pizza struct {
Toppings []string `json:"toppings"`
}
// String - Stringer interface
func (thisRef Pizza) String() string {
data, err := json.Marshal(thisRef)
if err != nil {
log.Println(err)
return ""
}
return string(data)
}
const TOP_N = 20
func main() {
orders, err := fetchData()
if err != nil {
log.Fatal(err)
}
data := map[string]int{}
for _, pizza := range orders {
for _, topping := range pizza.Toppings {
if _, ok := data[topping]; ok {
data[topping]++
} else {
data[topping] = 0
}
}
}
sortedData := rankByWordCount(data)
topN := len(sortedData)
if topN > TOP_N {
topN = TOP_N
}
for i := 0; i < TOP_N; i++ {
log.Println(fmt.Sprintf("%s - %d", sortedData[i].Key, sortedData[i].Value))
}
}
func fetchData() ([]Pizza, error) {
const url = "http://files.olo.com/pizzas.json"
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
client := http.Client{}
res, err := client.Do(req)
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
pizzas := []Pizza{}
err = json.Unmarshal(data, &pizzas)
if err != nil {
return nil, err
}
return pizzas, nil
}
func rankByWordCount(wordFrequencies map[string]int) PairList {
pl := make(PairList, len(wordFrequencies))
i := 0
for k, v := range wordFrequencies {
pl[i] = Pair{k, v}
i++
}
sort.Sort(sort.Reverse(pl))
return pl
}
type Pair struct {
Key string
Value int
}
type PairList []Pair
func (p PairList) Len() int { return len(p) }
func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }
func (p PairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment