summaryrefslogtreecommitdiff
path: root/Libraries/LibJS/Runtime/Value.cpp
diff options
context:
space:
mode:
authorAndreas Kling <kling@serenityos.org>2020-03-28 16:56:54 +0100
committerAndreas Kling <kling@serenityos.org>2020-03-28 16:56:54 +0100
commita3d92b1210bad42a7563b6a7d9a8787d6d2586ed (patch)
tree81e9ccca06853492b4cc8ddd20ba85b555288b8f /Libraries/LibJS/Runtime/Value.cpp
parent37fe16a99cd9ce31d6dba0b916be67929ae010a3 (diff)
downloadserenity-a3d92b1210bad42a7563b6a7d9a8787d6d2586ed.zip
LibJS: Implement the "instanceof" operator
This operator walks the prototype chain of the RHS value and looks for a "prototype" property with the same value as the prototype of the LHS. This is pretty cool. :^)
Diffstat (limited to 'Libraries/LibJS/Runtime/Value.cpp')
-rw-r--r--Libraries/LibJS/Runtime/Value.cpp22
1 files changed, 22 insertions, 0 deletions
diff --git a/Libraries/LibJS/Runtime/Value.cpp b/Libraries/LibJS/Runtime/Value.cpp
index 66582e4622..c36d358213 100644
--- a/Libraries/LibJS/Runtime/Value.cpp
+++ b/Libraries/LibJS/Runtime/Value.cpp
@@ -24,6 +24,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
+#include <AK/FlyString.h>
#include <AK/String.h>
#include <LibJS/Heap/Heap.h>
#include <LibJS/Runtime/Object.h>
@@ -253,6 +254,27 @@ Value eq(Value lhs, Value rhs)
return Value(false);
}
+Value instance_of(Value lhs, Value rhs)
+{
+ if (!lhs.is_object() || !rhs.is_object())
+ return Value(false);
+
+ auto* instance_prototype = lhs.as_object()->prototype();
+
+ if (!instance_prototype)
+ return Value(false);
+
+ for (auto* constructor_object = rhs.as_object(); constructor_object; constructor_object = constructor_object->prototype()) {
+ auto prototype_property = constructor_object->get_own_property(*constructor_object, "prototype");
+ if (!prototype_property.has_value())
+ continue;
+ if (prototype_property.value().is_object() && prototype_property.value().as_object() == instance_prototype)
+ return Value(true);
+ }
+
+ return Value(false);
+}
+
const LogStream& operator<<(const LogStream& stream, const Value& value)
{
return stream << value.to_string();