Created
December 3, 2021 06:58
-
-
Save Mo3g4u/d5ca46a5b5a8db6ed3f37b0900371da8 to your computer and use it in GitHub Desktop.
bimap
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
package bimap | |
import ( | |
"sync" | |
"github.com/artis-inc/axis-shared/log" | |
) | |
// 方向の定義 | |
const ( | |
// フロントエンドから渡されたデータをバックエンド用に変換する | |
ToBackend = "to-backend" | |
// バックエンドのデータをフロントエンド用に変換する | |
ToFrontend = "to-frontend" | |
) | |
// 双方向の変換用map | |
// | |
// 種類 - 方向(ToBackend | ToFrontend) - key - value | |
type BiMap struct { | |
biMap map[string]map[string]map[string]string | |
mu sync.Mutex | |
} | |
func NewBiMap() *BiMap { | |
return &BiMap{} | |
} | |
// バックエンド向けのmapデータを元に双方向mapに値を登録します | |
func (b *BiMap) RegisterBiMapToBE(category string, m map[string]string) { | |
b.mu.Lock() | |
defer b.mu.Unlock() | |
// 初期化処理 | |
if b.biMap == nil { | |
b.biMap = make(map[string]map[string]map[string]string) | |
} | |
_, ok := b.biMap[category] | |
if ok { | |
panic("そのカテゴリは既に登録済です") | |
} | |
if !ok { | |
b.biMap[category] = map[string]map[string]string{ | |
ToBackend: make(map[string]string), | |
ToFrontend: make(map[string]string), | |
} | |
} | |
// 双方向の登録 | |
for key, value := range m { | |
b.biMap[category][ToBackend][key] = value | |
b.biMap[category][ToFrontend][value] = key | |
} | |
} | |
// バックエンド向けの値取り出しです | |
func (b *BiMap) ToBE(category, key string) string { | |
_, ok := b.biMap[category] | |
if !ok { | |
log.Error("未定義のカテゴリーです") | |
return "" | |
} | |
v, ok := b.biMap[category][ToBackend][key] | |
if !ok { | |
log.Error("未定義のキーです") | |
return "" | |
} | |
return v | |
} | |
// フロントエンド向けの値取り出しです | |
func (b *BiMap) ToFE(category, key string) string { | |
_, ok := b.biMap[category] | |
if !ok { | |
log.Error("未定義のカテゴリーです") | |
return "" | |
} | |
v, ok := b.biMap[category][ToFrontend][key] | |
if !ok { | |
log.Error("未定義のキーです") | |
return "" | |
} | |
return v | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment