Skip to content

Instantly share code, notes, and snippets.

@fvbock
Created March 15, 2013 09:23
Show Gist options
  • Save fvbock/5168574 to your computer and use it in GitHub Desktop.
Save fvbock/5168574 to your computer and use it in GitHub Desktop.
functions/io_streams
package main
import (
"fmt"
"time"
"math/rand"
"sort"
)
type Entity struct {
Id string
Rank float64
}
func (e *Entity) String() string {
return fmt.Sprintf("<Entity: %s, Rank: %v>", e.Id, e.Rank)
}
type EntityList struct {
Entries []*Entity
Origin string
EntryOrder []int
}
func (e *EntityList) String() string {
var entryRepr string
for _, i := range e.EntryOrder {
entryRepr += fmt.Sprintf("%v ", *e.Entries[i])
}
return fmt.Sprintf("<EntityList: %s>", entryRepr)
}
func NewEntityList(origin string) *EntityList {
return &EntityList{
Origin: origin,
}
}
func search() chan *Entity {
ch := make(chan *Entity, 100)
startTime := time.Now()
go func() {
for i := 0; i < 10; i++ {
res := &Entity{
Id: fmt.Sprintf("ID_%v", i),
}
fmt.Println("found: ", res)
ch <- res
time.Sleep(20 * time.Millisecond)
}
close(ch)
fmt.Printf("Searching took: %v\n", time.Since(startTime))
}()
return ch
}
func rank(in chan *Entity) chan *Entity {
out := make(chan *Entity, 100)
startTime := time.Now()
go func() {
for {
res, open := <-in
if !open {
break
}
res.Rank = rand.Float64() * 10
fmt.Println("ranked: ", res)
time.Sleep(100 * time.Millisecond)
out <- res
}
close(out)
fmt.Printf("Ranking took: %v\n", time.Since(startTime))
}()
return out
}
func getSortedList() (sorted *EntityList) {
sorted = NewEntityList("SEARCH")
searchResults := search()
ranked := rank(searchResults)
rankMap := make(map[float64]int)
ranks := []float64{}
for {
rankedRes, open := <-ranked
if !open {
break
}
sorted.Entries = append(sorted.Entries, rankedRes)
rankMap[rankedRes.Rank] = len(sorted.Entries) - 1
ranks = append(ranks, rankedRes.Rank)
}
fmt.Println(ranks)
sort.Float64s(ranks)
fmt.Println(ranks)
sorted.EntryOrder = make([]int, len(sorted.Entries))
for n, r := range ranks {
sorted.EntryOrder[n] = rankMap[r]
}
fmt.Println("+++", sorted.EntryOrder)
return sorted
}
func main() {
startTime := time.Now()
results := getSortedList()
fmt.Printf("Searching,Ranking, Sorting took: %v\n", time.Since(startTime))
fmt.Println("GOT THIS: ", results)
fmt.Println("Done.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment