refactor objects
This commit is contained in:
@@ -3,7 +3,6 @@ package object
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -12,29 +11,6 @@ type HashKey struct {
|
||||
Value uint64
|
||||
}
|
||||
|
||||
func (b Boolean) HashKey() HashKey {
|
||||
var value uint64
|
||||
|
||||
if b.Value {
|
||||
value = 1
|
||||
} else {
|
||||
value = 0
|
||||
}
|
||||
|
||||
return HashKey{Type: b.Type(), Value: value}
|
||||
}
|
||||
|
||||
func (i Integer) HashKey() HashKey {
|
||||
return HashKey{Type: i.Type(), Value: uint64(i.Value)}
|
||||
}
|
||||
|
||||
func (s String) HashKey() HashKey {
|
||||
h := fnv.New64a()
|
||||
h.Write([]byte(s.Value))
|
||||
|
||||
return HashKey{Type: s.Type(), Value: h.Sum64()}
|
||||
}
|
||||
|
||||
type HashPair struct {
|
||||
Key Object
|
||||
Value Object
|
||||
@@ -91,12 +67,12 @@ func (h *Hash) Add(other Object) (Object, error) {
|
||||
}
|
||||
|
||||
func (h *Hash) Get(index Object) (Object, error) {
|
||||
key, ok := index.(Hashable)
|
||||
key, ok := index.(Hasher)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid hash key %s", index.Type())
|
||||
}
|
||||
|
||||
pair, found := h.Pairs[key.HashKey()]
|
||||
pair, found := h.Pairs[key.Hash()]
|
||||
if !found {
|
||||
return Null{}, nil
|
||||
}
|
||||
@@ -105,12 +81,12 @@ func (h *Hash) Get(index Object) (Object, error) {
|
||||
}
|
||||
|
||||
func (h *Hash) Set(index, other Object) error {
|
||||
key, ok := index.(Hashable)
|
||||
key, ok := index.(Hasher)
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid hash key %s", index.Type())
|
||||
}
|
||||
|
||||
h.Pairs[key.HashKey()] = HashPair{Key: index, Value: other}
|
||||
h.Pairs[key.Hash()] = HashPair{Key: index, Value: other}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -122,8 +98,8 @@ func (h *Hash) Compare(other Object) int {
|
||||
}
|
||||
for _, pair := range h.Pairs {
|
||||
left := pair.Value
|
||||
hashed := left.(Hashable)
|
||||
right, ok := obj.Pairs[hashed.HashKey()]
|
||||
hashed := left.(Hasher)
|
||||
right, ok := obj.Pairs[hashed.Hash()]
|
||||
if !ok {
|
||||
return -1
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user