From 1ba2e6768dbaeec0208e84dd0d2606c96baf932b Mon Sep 17 00:00:00 2001 From: Linus Groh Date: Fri, 1 May 2020 13:20:47 +0100 Subject: [PATCH] LibJS: Implement indexed access for StringObject --- Libraries/LibJS/Runtime/Object.cpp | 8 ++++++++ .../Tests/indexed-access-string-object.js | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 Libraries/LibJS/Tests/indexed-access-string-object.js diff --git a/Libraries/LibJS/Runtime/Object.cpp b/Libraries/LibJS/Runtime/Object.cpp index 34ee9e91efee84..696c1142cda9de 100644 --- a/Libraries/LibJS/Runtime/Object.cpp +++ b/Libraries/LibJS/Runtime/Object.cpp @@ -272,6 +272,12 @@ Value Object::get_by_index(i32 property_index) const const Object* object = this; while (object) { + if (is_string_object()) { + auto& string = static_cast(this)->primitive_string().string(); + if (property_index < (i32)string.length()) + return js_string(heap(), string.substring(property_index, 1)); + return js_undefined(); + } if (static_cast(property_index) < object->m_elements.size()) { auto value = object->m_elements[property_index]; if (value.is_empty()) @@ -397,6 +403,8 @@ bool Object::has_own_property(const FlyString& property_name) const bool ok; i32 property_index = property_name.to_int(ok); if (ok && property_index >= 0) { + if (is_string_object()) + return property_index < (i32)static_cast(this)->primitive_string().string().length(); if (static_cast(property_index) >= m_elements.size()) return false; return !m_elements[property_index].is_empty(); diff --git a/Libraries/LibJS/Tests/indexed-access-string-object.js b/Libraries/LibJS/Tests/indexed-access-string-object.js new file mode 100644 index 00000000000000..114594e542cc66 --- /dev/null +++ b/Libraries/LibJS/Tests/indexed-access-string-object.js @@ -0,0 +1,19 @@ +load("test-common.js"); + +try { + var s = "foo"; + assert(s[0] === "f"); + assert(s[1] === "o"); + assert(s[2] === "o"); + assert(s[3] === undefined); + + var o = new String("bar"); + assert(o[0] === "b"); + assert(o[1] === "a"); + assert(o[2] === "r"); + assert(o[3] === undefined); + + console.log("PASS"); +} catch (e) { + console.log("FAIL: " + e); +}