Skip to content

Commit

Permalink
LibJS: Implement indexed access for StringObject
Browse files Browse the repository at this point in the history
  • Loading branch information
linusg authored and awesomekling committed May 1, 2020
1 parent a81bce8 commit 1ba2e67
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
8 changes: 8 additions & 0 deletions Libraries/LibJS/Runtime/Object.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<const StringObject*>(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<size_t>(property_index) < object->m_elements.size()) {
auto value = object->m_elements[property_index];
if (value.is_empty())
Expand Down Expand Up @@ -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<const StringObject*>(this)->primitive_string().string().length();
if (static_cast<size_t>(property_index) >= m_elements.size())
return false;
return !m_elements[property_index].is_empty();
Expand Down
19 changes: 19 additions & 0 deletions Libraries/LibJS/Tests/indexed-access-string-object.js
Original file line number Diff line number Diff line change
@@ -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);
}

0 comments on commit 1ba2e67

Please sign in to comment.