From 603620b7394da5855e2255790bfea9ad7d80ddf9 Mon Sep 17 00:00:00 2001 From: Scott Kyle Date: Fri, 4 Mar 2022 08:02:17 -0800 Subject: [PATCH] Add asBool() method Summary: Changelog: [General][Added] - Add asBool() method to JSI Reviewed By: mhorowitz Differential Revision: D34630901 fbshipit-source-id: 3007784618fcc0f7828eee42de5cbf2bd71258c5 --- ReactCommon/jsi/jsi/jsi.cpp | 9 +++++++++ ReactCommon/jsi/jsi/jsi.h | 4 ++++ ReactCommon/jsi/jsi/test/testlib.cpp | 2 ++ 3 files changed, 15 insertions(+) diff --git a/ReactCommon/jsi/jsi/jsi.cpp b/ReactCommon/jsi/jsi/jsi.cpp index a40fe8664d7bc3..4dfb1a04af2f76 100644 --- a/ReactCommon/jsi/jsi/jsi.cpp +++ b/ReactCommon/jsi/jsi/jsi.cpp @@ -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( diff --git a/ReactCommon/jsi/jsi/jsi.h b/ReactCommon/jsi/jsi/jsi.h index 816d563cff3c81..d522fa7bb0d280 100644 --- a/ReactCommon/jsi/jsi/jsi.h +++ b/ReactCommon/jsi/jsi/jsi.h @@ -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()); diff --git a/ReactCommon/jsi/jsi/test/testlib.cpp b/ReactCommon/jsi/jsi/test/testlib.cpp index 87dffaa56debed..ef325e9bd2f7e5 100644 --- a/ReactCommon/jsi/jsi/test/testlib.cpp +++ b/ReactCommon/jsi/jsi/test/testlib.cpp @@ -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(