aboutsummaryrefslogtreecommitdiff
path: root/evaluator/evaluator_test.go
diff options
context:
space:
mode:
authorBobby <[email protected]>2024-04-10 20:42:41 +0000
committerBobby <[email protected]>2024-04-10 20:42:41 +0000
commitca46690f9166681e4b32af90e28fb215c12f76c0 (patch)
tree1b8ac7bf26616bcc0bdc3038221997d30d66d751 /evaluator/evaluator_test.go
parente7b7baba5e6485ae6e241eee4c3f30557afa0fa8 (diff)
downloadmana-ca46690f9166681e4b32af90e28fb215c12f76c0.tar.xz
mana-ca46690f9166681e4b32af90e28fb215c12f76c0.zip
hashes
Diffstat (limited to 'evaluator/evaluator_test.go')
-rw-r--r--evaluator/evaluator_test.go90
1 files changed, 90 insertions, 0 deletions
diff --git a/evaluator/evaluator_test.go b/evaluator/evaluator_test.go
index 3c72cda..f1d28d0 100644
--- a/evaluator/evaluator_test.go
+++ b/evaluator/evaluator_test.go
@@ -185,6 +185,10 @@ func TestErrorhandling(t *testing.T) {
`"Hello" - "World"`,
"unknown operator: STRING - STRING",
},
+ {
+ `{"name": "Monkey"}[fn(x) { x }];`,
+ "unusable as hash key: FUNCTION",
+ },
}
for _, tt := range tests {
@@ -456,3 +460,89 @@ func TestArrayIndexExpressions(t *testing.T) {
}
}
}
+
+func TestHashLiterals(t *testing.T) {
+ input := `let two = "two";
+ {
+ "one": 10 - 9,
+ two: 1 + 1,
+ "thr" + "ee": 6 / 2,
+ 4: 4,
+ true: 5,
+ false: 6
+ }`
+
+ evaluated := testEval(input)
+ result, ok := evaluated.(*object.Hash)
+ if !ok {
+ t.Fatalf("Eval didn't return Hash. got=%T (%+v)", evaluated, evaluated)
+ }
+
+ expected := map[object.HashKey]int64{
+ (&object.String{Value: "one"}).HashKey(): 1,
+ (&object.String{Value: "two"}).HashKey(): 2,
+ (&object.String{Value: "three"}).HashKey(): 3,
+ (&object.Integer{Value: 4}).HashKey(): 4,
+ TRUE.HashKey(): 5,
+ FALSE.HashKey(): 6,
+ }
+
+ if len(result.Pairs) != len(expected) {
+ t.Fatalf("Hash has wrong num of pairs. got=%d", len(result.Pairs))
+ }
+
+ for expectedKey, expectedValue := range expected {
+ pair, ok := result.Pairs[expectedKey]
+ if !ok {
+ t.Errorf("no pair for given key in Pairs")
+ }
+
+ testIntegerObject(t, pair.Value, expectedValue)
+ }
+}
+
+func TestHashIndexExpressions(t *testing.T) {
+ tests := []struct {
+ input string
+ expected interface{}
+ }{
+ {
+ `{"foo": 5}["foo"]`,
+ 5,
+ },
+ {
+ `{"foo": 5}["bar"]`,
+ nil,
+ },
+ {
+ `let key = "foo"; {"foo": 5}[key]`,
+ 5,
+ },
+ {
+ `{}["foo"]`,
+ nil,
+ },
+ {
+ `{5: 5}[5]`,
+ 5,
+ },
+ {
+ `{true: 5}[true]`,
+ 5,
+ },
+ {
+ `{false: 5}[false]`,
+ 5,
+ },
+ }
+
+ for _, tt := range tests {
+ evaluated := testEval(tt.input)
+ integer, ok := tt.expected.(int)
+ if ok {
+ testIntegerObject(t, evaluated, int64(integer))
+ } else {
+ testNullObject(t, evaluated)
+ }
+ }
+}