From 8c60ba1e4227383c81a1b6bbb94696d15d638a83 Mon Sep 17 00:00:00 2001 From: Emanuele Torre Date: Fri, 1 May 2020 07:14:57 +0200 Subject: [PATCH] LibJS: Implement console.count() --- Libraries/LibJS/Interpreter.h | 4 ++++ Libraries/LibJS/Runtime/ConsoleObject.cpp | 24 +++++++++++++++++++++++ Libraries/LibJS/Runtime/ConsoleObject.h | 1 + 3 files changed, 29 insertions(+) diff --git a/Libraries/LibJS/Interpreter.h b/Libraries/LibJS/Interpreter.h index 8ec4b6de15..b55b0fe996 100644 --- a/Libraries/LibJS/Interpreter.h +++ b/Libraries/LibJS/Interpreter.h @@ -162,6 +162,8 @@ public: Value last_value() const { return m_last_value; } + HashMap& console_counters() { return m_console_counters; } + private: Interpreter(); @@ -177,6 +179,8 @@ private: Exception* m_exception { nullptr }; ScopeType m_unwind_until { ScopeType::None }; + + HashMap m_console_counters; }; } diff --git a/Libraries/LibJS/Runtime/ConsoleObject.cpp b/Libraries/LibJS/Runtime/ConsoleObject.cpp index de61b1700e..8e8c9e2dcc 100644 --- a/Libraries/LibJS/Runtime/ConsoleObject.cpp +++ b/Libraries/LibJS/Runtime/ConsoleObject.cpp @@ -1,6 +1,7 @@ /* * Copyright (c) 2020, Andreas Kling * Copyright (c) 2020, Linus Groh + * Copyright (c) 2020, Emanuele Torre * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -27,6 +28,7 @@ #include #include +#include #include #include #include @@ -53,6 +55,7 @@ ConsoleObject::ConsoleObject() put_native_function("warn", warn); put_native_function("error", error); put_native_function("trace", trace); + put_native_function("count", count); } ConsoleObject::~ConsoleObject() @@ -109,4 +112,25 @@ Value ConsoleObject::trace(Interpreter& interpreter) return js_undefined(); } +Value ConsoleObject::count(Interpreter& interpreter) +{ + String counter_name; + if (!interpreter.argument_count()) + counter_name = "default"; + else + counter_name = interpreter.argument(0).to_string(); + + auto& counters = interpreter.console_counters(); + auto counter_value = counters.get(counter_name); + + if (counter_value.has_value()) { + printf("%s: %d\n", counter_name.characters(), counter_value.value() + 1); + counters.set(counter_name, counter_value.value() + 1); + } else { + printf("%s: 1\n", counter_name.characters()); + counters.set(counter_name, 1); + } + return js_undefined(); +} + } diff --git a/Libraries/LibJS/Runtime/ConsoleObject.h b/Libraries/LibJS/Runtime/ConsoleObject.h index 7aa58c8ce0..50874a357a 100644 --- a/Libraries/LibJS/Runtime/ConsoleObject.h +++ b/Libraries/LibJS/Runtime/ConsoleObject.h @@ -44,6 +44,7 @@ private: static Value warn(Interpreter&); static Value error(Interpreter&); static Value trace(Interpreter&); + static Value count(Interpreter&); }; }