Skip to content

Commit

Permalink
Add asBool() method
Browse files Browse the repository at this point in the history
Summary:
Changelog:
[General][Added] - Add asBool() method to JSI

Reviewed By: mhorowitz

Differential Revision: D34630901

fbshipit-source-id: 3007784618fcc0f7828eee42de5cbf2bd71258c5
  • Loading branch information
appden authored and facebook-github-bot committed Mar 4, 2022
1 parent 350f8c5 commit 603620b
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
9 changes: 9 additions & 0 deletions ReactCommon/jsi/jsi/jsi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,15 @@ bool Value::strictEquals(Runtime& runtime, const Value& a, const Value& b) {
return false;
}

bool Value::asBool() const {
if (!isBool()) {
throw JSINativeException(
"Value is " + kindToString(*this) + ", expected a boolean");
}

return getBool();
}

double Value::asNumber() const {
if (!isNumber()) {
throw JSINativeException(
Expand Down
4 changes: 4 additions & 0 deletions ReactCommon/jsi/jsi/jsi.h
Original file line number Diff line number Diff line change
Expand Up @@ -1078,6 +1078,10 @@ class JSI_EXPORT Value {
return data_.boolean;
}

/// \return the boolean value, or throws JSIException if not a
/// boolean.
bool asBool() const;

/// \return the number value, or asserts if not a number.
double getNumber() const {
assert(isNumber());
Expand Down
2 changes: 2 additions & 0 deletions ReactCommon/jsi/jsi/test/testlib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,8 @@ TEST_P(JSITest, ValueTest) {
EXPECT_EQ(eval("'str'").getString(rt).utf8(rt), "str");
EXPECT_TRUE(eval("[]").getObject(rt).isArray(rt));

EXPECT_TRUE(eval("true").asBool());
EXPECT_THROW(eval("123").asBool(), JSIException);
EXPECT_EQ(eval("456").asNumber(), 456);
EXPECT_THROW(eval("'word'").asNumber(), JSIException);
EXPECT_EQ(
Expand Down

0 comments on commit 603620b

Please sign in to comment.