mal-go/hash_map/hash_map.go
2025-11-05 06:28:42 -10:00

73 lines
1.2 KiB
Go

package hash_map
import (
"mal-go/utils"
"maps"
"strings"
)
// TODO: replace COW with proper HashArrayMappedTrie impelmentation of PersistentHashMap
type HashMap struct {
_map map[any]any
}
func New() *HashMap {
return new(HashMap).Init()
}
func Init(this *HashMap) *HashMap {
this._map = make(map[any]any)
return this
}
func (this *HashMap) Init() *HashMap {
return Init(this)
}
func Clone(this *HashMap) *HashMap {
if this == nil {
return nil
}
newMap := New().Init()
maps.Copy(newMap._map, this._map)
return newMap
}
func (this *HashMap) Clone() *HashMap {
return Clone(this)
}
func Conj(this *HashMap, key any, val any) *HashMap {
newMap := this.Clone()
newMap._map[key] = val
return newMap
}
func (this *HashMap) Conj(key any, val any) *HashMap {
return Conj(this, key, val)
}
func (this *HashMap) IsEmpty() bool {
return len(this._map) == 0
}
func (this *HashMap) String() string {
if this.IsEmpty() {
return "{}"
}
var sb strings.Builder
sb.WriteRune('{')
for key, val := range this._map {
sb.WriteString(utils.Stringify(key))
sb.WriteRune(' ')
sb.WriteString(utils.Stringify(val))
sb.WriteRune(',')
sb.WriteRune(' ')
}
return sb.String()[:sb.Len()-2] + "}"
}