Created
November 22, 2021 06:34
-
-
Save CAFxX/892e7e4361a08d975ec6262dff408f2c to your computer and use it in GitHub Desktop.
This file contains hidden or 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 container | |
type BijectiveMap[A, B comparable] struct { | |
m1 map[A]B | |
m2 map[B]A | |
} | |
func (m *BijectiveMap[A, B]) GetB(a A) (B, bool) { | |
if m.m1 == nil { | |
var zero B | |
return zero, false | |
} | |
b, exists := m.m1[a] | |
return b, exists | |
} | |
func (m *BijectiveMap[A, B]) GetA(b B) (A, bool) { | |
if m.m2 == nil { | |
var zero A | |
return zero, false | |
} | |
a, exists := m.m2[b] | |
return a, exists | |
} | |
func (m *BijectiveMap[A, B]) Set(a A, b B) (A, B, bool) { | |
if m.m1 == nil { | |
m.m1 = make(map[A]B) | |
m.m2 = make(map[B]A) | |
} | |
ob, exists := m.m1[a] | |
if ob == b { | |
return a, b, true | |
} | |
if exists { | |
delete(m.m2, ob) | |
} | |
m.m1[a] = b | |
m.m2[b] = a | |
return a, ob, exists | |
} | |
func (m *BijectiveMap[A, B]) DelB(a A) (B, bool) { | |
if m.m1 == nil { | |
var zero B | |
return zero, false | |
} | |
b, exists := m.m1[a] | |
if exists { | |
delete(m.m1, a) | |
delete(m.m2, b) | |
} | |
return b, exists | |
} | |
func (m *BijectiveMap[A, B]) DelA(b B) (A, bool) { | |
if m.m2 == nil { | |
var zero A | |
return zero, false | |
} | |
a, exists := m.m2[b] | |
if exists { | |
delete(m.m1, a) | |
delete(m.m2, b) | |
} | |
return a, exists | |
} | |
func (m *BijectiveMap[A, B]) ForEach(fn func(A, B) bool) { | |
for k, v := range m.m1 { | |
if !fn(k, v) { | |
return | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment