Skip to content

Commit

Permalink
object/hash: add get method with default if key not exists
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkusFreitag committed Dec 4, 2022
1 parent 917b487 commit b741848
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
19 changes: 19 additions & 0 deletions object/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]
},
},
}
}

Expand Down
2 changes: 2 additions & 0 deletions object/hash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit b741848

Please sign in to comment.