Last active
February 22, 2023 00:50
-
-
Save xmapst/7d41516a644acd900bb3096573947e58 to your computer and use it in GitHub Desktop.
CompareInteger
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 compare | |
type signed interface { | |
~int | ~int8 | ~int16 | ~int32 | ~int64 | |
} | |
type unsigned interface { | |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | |
} | |
type integer interface { | |
signed | unsigned | |
} | |
type compare[T integer] struct { | |
source, target, result []*T | |
} | |
func Integer[T integer](source, target []T) []T { | |
c := compare[T]{} | |
c.init(source, target) | |
for k, v := range c.target { | |
if !c.contains(c.source, v) { | |
c.result[k] = v | |
c.source = append(c.source, v) | |
c.target[k] = nil | |
} | |
} | |
for k, v := range c.target { | |
if v == nil { | |
continue | |
} | |
c.result[k] = c.compare(v) | |
} | |
return c.unConvert() | |
} | |
func (c *compare[T]) init(source, target []T) { | |
c.source = c.removeDuplicates(c.convert(source)) | |
c.target = c.removeDuplicates(c.convert(target)) | |
c.result = make([]*T, len(target)) | |
} | |
func (c *compare[T]) compare(e *T) *T { | |
if c.contains(c.source, e) { | |
*e += 1 | |
return c.compare(e) | |
} | |
c.source = append(c.source, e) | |
return e | |
} | |
func (c *compare[T]) removeDuplicates(source []*T) (target []*T) { | |
for _, v := range source { | |
if !c.contains(target, v) { | |
target = append(target, v) | |
} | |
} | |
return | |
} | |
func (c *compare[T]) contains(source []*T, target *T) bool { | |
for _, v := range source { | |
if *v == *target { | |
return true | |
} | |
} | |
return false | |
} | |
func (c *compare[T]) convert(s []T) (e []*T) { | |
for _, v := range s { | |
e = append(e, func(v T) *T { | |
return &v | |
}(v)) | |
} | |
return e | |
} | |
func (c *compare[T]) unConvert() (e []T) { | |
for _, v := range c.result { | |
e = append(e, func(v *T) T { | |
return *v | |
}(v)) | |
} | |
return e | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment