From 1cc69fffbbfa40cd838250e2af2b00fa0b7aab9b Mon Sep 17 00:00:00 2001 From: Stefan Marr Date: Thu, 4 Apr 2024 13:45:34 +0100 Subject: [PATCH] Add primitive implementation for String>>#charAt: Signed-off-by: Stefan Marr --- src/som/primitives/string_primitives.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/som/primitives/string_primitives.py b/src/som/primitives/string_primitives.py index 680b54f8..5ac79afd 100644 --- a/src/som/primitives/string_primitives.py +++ b/src/som/primitives/string_primitives.py @@ -39,6 +39,15 @@ def _substring(rcvr, start, end): return String(string[s:e]) +def _char_at(rcvr, idx): + i = idx.get_embedded_integer() - 1 + string = rcvr.get_embedded_string() + + if i < 0 or i >= len(string): + return String("Error - index out of bounds") + return String(string[i]) + + def _hashcode(rcvr): return Integer(compute_hash(rcvr.get_embedded_string())) @@ -81,6 +90,7 @@ def _is_digits(self): class StringPrimitivesBase(Primitives): def install_primitives(self): + self._install_instance_primitive(BinaryPrimitive("charAt:", _char_at)) self._install_instance_primitive(BinaryPrimitive("concatenate:", _concat)) self._install_instance_primitive(UnaryPrimitive("asSymbol", _as_symbol)) self._install_instance_primitive(UnaryPrimitive("length", _length))