Skip to content

Commit

Permalink
support returning float
Browse files Browse the repository at this point in the history
  • Loading branch information
hmsk committed Jun 19, 2024
1 parent 36bcf13 commit 21f887c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
13 changes: 10 additions & 3 deletions ext/quickjsrb/quickjsrb.c
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ VALUE rb_module_eval_js_code(
JSValue res = JS_Eval(ctx, code, strlen(code), "<code>", JS_EVAL_TYPE_GLOBAL);

VALUE result;
int r = 0;
if (JS_IsException(res)) {
rb_raise(rb_eRuntimeError, "Something happened by evaluating as JavaScript code");
result = Qnil;
Expand All @@ -71,8 +70,16 @@ VALUE rb_module_eval_js_code(
} else if (JS_VALUE_IS_NAN(res)) {
result = ID2SYM(rb_intern(nanId));
} else if (JS_IsNumber(res)) {
JS_ToInt32(ctx, &r, res);
result = INT2NUM(r);
int tag = JS_VALUE_GET_TAG(res);
if (JS_TAG_IS_FLOAT64(tag)) {
double double_res;
JS_ToFloat64(ctx, &double_res, res);
result = DBL2NUM(double_res);
} else {
int int_res;
JS_ToInt32(ctx, &int_res, res);
result = INT2NUM(int_res);
}
} else if (JS_IsString(res)) {
JSValue maybeString = JS_ToString(ctx, res);
const char *msg = JS_ToCString(ctx, maybeString);
Expand Down
5 changes: 5 additions & 0 deletions test/quickjs_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ class QuickjsTest < Test::Unit::TestCase
assert_equal(::Quickjs.evalCode("const func = () => 8; func();"), 8)
end

test "support returning float" do
assert_equal(::Quickjs.evalCode("1.0"), 1.0)
assert_equal(::Quickjs.evalCode("2 ** 0.5"), 1.4142135623730951)
end

test "support returning boolean" do
assert_equal(::Quickjs.evalCode("false"), false)
assert_equal(::Quickjs.evalCode("true"), true)
Expand Down

0 comments on commit 21f887c

Please sign in to comment.