Skip to content

Commit

Permalink
feat(value): add is_function (#39)
Browse files Browse the repository at this point in the history
Signed-off-by: Tony Gorez <gorez.tony@gmail.com>
  • Loading branch information
tony-go authored Feb 22, 2024
1 parent 6e72884 commit 30311a3
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/engine/include/includejs/engine_value.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ class INCLUDEJS_ENGINE_EXPORT Value {
auto is_undefined() const -> bool;
auto is_null() const -> bool;
auto is_array() const -> bool;
auto is_function() const -> bool;
auto to_number() const -> double;
auto to_string() const -> std::string;
auto to_boolean() const -> bool;
Expand Down
11 changes: 11 additions & 0 deletions src/engine/javascript_core/engine_value.cc
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,17 @@ auto Value::is_null() const -> bool {
return JSValueIsNull(this->internal->context, this->internal->value);
}

auto Value::is_function() const -> bool {
if (!is_object()) {
return false;
}

JSObjectRef object =
get_current_object(this->internal->context, this->internal->value);

return JSObjectIsFunction(this->internal->context, object);
}

auto Value::to_number() const -> double {
assert(is_number());
JSValueRef exception = nullptr;
Expand Down
1 change: 1 addition & 0 deletions test/engine/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ add_executable(includejs_engine_unit
engine_stacktraces_test.cc
engine_value_object_test.cc
engine_value_array_test.cc
engine_value_function_test.cc
engine_value_undefined_test.cc
engine_value_null_test.cc)

Expand Down
20 changes: 20 additions & 0 deletions test/engine/engine_value_function_test.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#include <gtest/gtest.h>

#include <includejs/engine.h>

TEST(IncludeJS_Engine, is_function) {
sourcemeta::includejs::Engine engine;

auto obj = engine.context().make_object();
obj.set(
"foo",
[](std::vector<sourcemeta::includejs::Value> arguments)
-> sourcemeta::includejs::Value { return std::move(arguments[0]); });
obj.set("bar", engine.context().from(42));

EXPECT_TRUE(obj.at("foo").has_value());
EXPECT_TRUE(obj.at("foo").value().is_function());

EXPECT_TRUE(obj.at("bar").has_value());
EXPECT_FALSE(obj.at("bar").value().is_function());
}

0 comments on commit 30311a3

Please sign in to comment.