Skip to content

Commit

Permalink
LibJS: Implement console.count()
Browse files Browse the repository at this point in the history
  • Loading branch information
emanuele6 authored and awesomekling committed May 1, 2020
1 parent 28ef654 commit 8c60ba1
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Libraries/LibJS/Interpreter.h
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,8 @@ class Interpreter {

Value last_value() const { return m_last_value; }

HashMap<String, unsigned>& console_counters() { return m_console_counters; }

private:
Interpreter();

Expand All @@ -177,6 +179,8 @@ class Interpreter {
Exception* m_exception { nullptr };

ScopeType m_unwind_until { ScopeType::None };

HashMap<String, unsigned> m_console_counters;
};

}
24 changes: 24 additions & 0 deletions Libraries/LibJS/Runtime/ConsoleObject.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/*
* Copyright (c) 2020, Andreas Kling <[email protected]>
* Copyright (c) 2020, Linus Groh <[email protected]>
* Copyright (c) 2020, Emanuele Torre <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
Expand All @@ -27,6 +28,7 @@

#include <AK/FlyString.h>
#include <AK/Function.h>
#include <AK/HashMap.h>
#include <LibJS/Interpreter.h>
#include <LibJS/Runtime/ConsoleObject.h>
#include <LibJS/Runtime/GlobalObject.h>
Expand All @@ -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()
Expand Down Expand Up @@ -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();
}

}
1 change: 1 addition & 0 deletions Libraries/LibJS/Runtime/ConsoleObject.h
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ class ConsoleObject final : public Object {
static Value warn(Interpreter&);
static Value error(Interpreter&);
static Value trace(Interpreter&);
static Value count(Interpreter&);
};

}

0 comments on commit 8c60ba1

Please sign in to comment.