Last active
September 13, 2017 23:17
-
-
Save brydavis/456add2c93934e3760c38011a2edff9b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// heavily borrowed from Rosetta Code example | |
package main | |
import ( | |
"fmt" | |
) | |
type row map[string]interface{} | |
var ( | |
tableA = []row{ | |
row{"name": "Jonah", "female": 0, "age": 27}, | |
row{"name": "Alan", "female": 0, "age": 18}, | |
row{"name": "Glory", "female": 0, "age": 28}, | |
row{"name": "Popeye", "female": 0, "age": 18}, | |
row{"name": "Alan", "female": 1, "age": 28}, | |
} | |
tableB = []row{ | |
row{"name": "Jonah", "female": 0, "fear": "Whales"}, | |
row{"name": "Jonah", "female": 0, "fear": "Spiders"}, | |
row{"name": "Alan", "female": 0, "fear": "Ghosts"}, | |
row{"name": "Alan", "female": 1, "fear": "Zombies"}, | |
row{"name": "Glory", "female": 0, "fear": "Buffy"}, | |
} | |
) | |
func main() { | |
Join(tableA, tableB, "name", "female") | |
// t := Join(tableA, tableB, "name", "female") | |
// j, _ := json.MarshalIndent(t, "", "\t") | |
// fmt.Println(string(j)) | |
} | |
func Join(t1, t2 []row, on ...string) []map[string]interface{} { | |
m := []map[string]interface{}{} | |
for a := 0; a < len(t1); a++ { | |
for b := 0; b < len(t2); b++ { | |
var matches int | |
for i := range on { | |
if t1[a][on[i]] == t2[b][on[i]] { | |
matches += 1 | |
} | |
} | |
if len(on) == matches { | |
fmt.Println(t1[a], t2[b]) | |
r := row{} | |
for k, v := range t1[a] { | |
r[k] = v | |
} | |
for k, v := range t2[b] { | |
r[k] = v | |
} | |
m = append(m, r) | |
} | |
} | |
} | |
return m | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment