From b74184833a30518b5039638a1e94e915fe019b10 Mon Sep 17 00:00:00 2001 From: Markus Freitag Date: Sun, 4 Dec 2022 11:15:00 +0100 Subject: [PATCH] object/hash: add get method with default if key not exists --- object/hash.go | 19 +++++++++++++++++++ object/hash_test.go | 2 ++ 2 files changed, 21 insertions(+) diff --git a/object/hash.go b/object/hash.go index 4a38269..65c2300 100644 --- a/object/hash.go +++ b/object/hash.go @@ -122,6 +122,25 @@ func init() { return NewArray(values) }, }, + "get": ObjectMethod{ + Layout: MethodLayout{ + ArgPattern: Args( + Arg(ANY_OBJ...), + Arg(ANY_OBJ...), + ), + ReturnPattern: Args( + Arg(ANY_OBJ...), + ), + }, + method: func(o Object, args []Object, _ Environment) Object { + h := o.(*Hash) + k := args[0].(Hashable) + if pair, ok := h.Pairs[k.HashKey()]; ok { + return pair.Value + } + return args[1] + }, + }, } } diff --git a/object/hash_test.go b/object/hash_test.go index 8849cdb..bd26ac7 100644 --- a/object/hash_test.go +++ b/object/hash_test.go @@ -31,6 +31,8 @@ func TestHashObjectMethods(t *testing.T) { {`{"a": "b"}.to_json()`, `{"a":"b"}`}, {`{1: "b"}.to_json()`, `{"1":"b"}`}, {`{true: "b"}.to_json()`, `{"true":"b"}`}, + {`{"a": 1, "b": 2}.get("a", 10)`, `1`}, + {`{"a": 1, "b": 2}.get("c", 10)`, `10`}, } testInput(t, tests)