Skip to content

Commit

Permalink
Merge pull request #10 from vaskoz/schemamapping
Browse files Browse the repository at this point in the history
schema mapping problem
  • Loading branch information
vaskoz committed Sep 8, 2018
2 parents 26b21b8 + e1978b3 commit 570c632
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
30 changes: 30 additions & 0 deletions schema_mapping/schema.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package schema

// Field represents a field that has aliases used by other fields.
type Field struct {
name string
aliases []string
}

// Schema is a list of Fields.
type Schema struct {
fields []Field
}

// Mapping takes two schemas and returns a map of field names between schemas.
func Mapping(src, target Schema) map[string]string {
aliasMap := make(map[string]string)
for _, field := range target.fields {
aliasMap[field.name] = field.name
for _, alias := range field.aliases {
aliasMap[alias] = field.name
}
}
result := make(map[string]string)
for _, field := range src.fields {
if _, found := aliasMap[field.name]; found {
result[field.name] = aliasMap[field.name]
}
}
return result
}
47 changes: 47 additions & 0 deletions schema_mapping/schema_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package schema

import (
"reflect"
"testing"
)

var testcases = []struct {
src, target Schema
expected map[string]string
}{
{src: Schema{[]Field{{"country", []string{"cnt", "countryLong"}}}},
target: Schema{[]Field{{"countryLong", []string{"country"}}}},
expected: map[string]string{"country": "countryLong"}},
{src: Schema{[]Field{
{"country", []string{"nationality"}},
{"state", []string{"st", "territory"}},
{"city", []string{"cty", "burrow"}},
}},
target: Schema{[]Field{
{"st", []string{"not country", "state", "sttt"}},
{"burrow", []string{"hometown", "city"}},
{"nationality", []string{"country", "nation", "residency"}},
}},
expected: map[string]string{
"country": "nationality",
"state": "st",
"city": "burrow",
}},
}

func TestMapping(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := Mapping(tc.src, tc.target); !reflect.DeepEqual(result, tc.expected) {
t.Errorf("Expected %v but got %v", tc.expected, result)
}
}
}

func BenchmarkMapping(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
Mapping(tc.src, tc.target)
}
}
}

0 comments on commit 570c632

Please sign in to comment.