Skip to content

Commit

Permalink
add support for index operator on string
Browse files Browse the repository at this point in the history
Signed-off-by: Flipez <code@brauser.io>
  • Loading branch information
Flipez committed Sep 28, 2021
1 parent aaa900e commit f7babd3
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions evaluator/evaluator.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,11 +174,25 @@ func evalIndexExpression(left, index object.Object) object.Object {
return evalArrayIndexExpression(left, index)
case left.Type() == object.HASH_OBJ:
return evalHashIndexExpression(left, index)
case left.Type() == object.STRING_OBJ:
return evalStringIndexExpression(left, index)
default:
return newError("index operator not supported: %s", left.Type())
}
}

func evalStringIndexExpression(left, index object.Object) object.Object {
stringObject := left.(*object.String)
idx := index.(*object.Integer).Value
max := int64(len(stringObject.Value) - 1)

if idx < 0 || idx > max {
return NULL
}

return &object.String{Value: string(stringObject.Value[idx])}
}

func evalHashIndexExpression(hash, index object.Object) object.Object {
hashObject := hash.(*object.Hash)
key, ok := index.(object.Hashable)
Expand Down

0 comments on commit f7babd3

Please sign in to comment.