srctree

Robin Linden parent ac8a94a8 d9eb03b1
js: Make it possible to convert Values into booleans

inlinesplit
js/ast.h added: 38, removed: 2, total 36
@@ -56,6 +56,16 @@ public:
std::shared_ptr<Function const> as_function() const { return std::get<std::shared_ptr<Function>>(value_); }
std::vector<Value> const &as_vector() const { return std::get<std::vector<Value>>(value_); }
 
bool as_bool() const {
// TODO(robinlinden): false, 0n, null, NaN, objects with an [[IsHTMLDDA]] internal slot.
// https://developer.mozilla.org/en-US/docs/Glossary/Falsy
if (*this == Value{0} || *this == Value{-0} || *this == Value{""} || *this == Value{}) {
return false;
}
 
return true;
}
 
[[nodiscard]] bool operator==(Value const &) const = default;
 
private:
 
filename was Deleted added: 38, removed: 2, total 36
@@ -0,0 +1,26 @@
// SPDX-FileCopyrightText: 2022 Robin Lindén <dev@robinlinden.eu>
//
// SPDX-License-Identifier: BSD-2-Clause
 
#include "js/ast.h"
 
#include "etest/etest.h"
 
using namespace js::ast;
using etest::expect_eq;
 
int main() {
etest::test("Value: as_bool", [] {
expect_eq(Value{""}.as_bool(), false);
expect_eq(Value{0}.as_bool(), false);
expect_eq(Value{-0}.as_bool(), false);
expect_eq(Value{}.as_bool(), false);
 
expect_eq(Value{" "}.as_bool(), true);
expect_eq(Value{1}.as_bool(), true);
expect_eq(Value{-0.001}.as_bool(), true);
expect_eq(Value{std::vector<Value>{}}.as_bool(), true);
});
 
return etest::run_all_tests();
}