From 4d3e39c6191c49a54e3d1ee757b32ed905c4c0c3 Mon Sep 17 00:00:00 2001 From: Valentin Bartenev Date: Tue, 8 Nov 2016 22:09:40 +0300 Subject: [PATCH] Math.hypot() method. --- njs/njs_math.c | 46 ++++++++++++++++++++++++++++++++++++++++ njs/test/njs_unit_test.c | 21 ++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/njs/njs_math.c b/njs/njs_math.c index 7b0297ee..c65a596f 100644 --- a/njs/njs_math.c +++ b/njs/njs_math.c @@ -19,6 +19,7 @@ #include #include #include +#include static njs_ret_t @@ -196,6 +197,44 @@ njs_object_math_floor(njs_vm_t *vm, njs_value_t *args, nxt_uint_t nargs, } +static njs_ret_t +njs_object_math_hypot(njs_vm_t *vm, njs_value_t *args, nxt_uint_t nargs, + njs_index_t unused) +{ + double num; + nxt_uint_t i; + + for (i = 1; i < nargs; i++) { + if (!njs_is_numeric(&args[i])) { + vm->frame->trap_scratch.data.u.value = &args[i]; + + return NJS_TRAP_NUMBER_ARG; + } + } + + num = (nargs > 1) ? fabs(args[1].data.u.number) : 0; + + for (i = 2; i < nargs; i++) { + num = hypot(num, args[i].data.u.number); + + if (num == HUGE_VAL) { + /* HUGE_VAL is equal to INFINITY on IEEE-754 systems. */ + + if (nxt_slow_path(errno == ERANGE)) { + vm->exception = &njs_exception_range_error; + return NXT_ERROR; + } + + break; + } + } + + njs_number_set(&vm->retval, num); + + return NXT_OK; +} + + static njs_ret_t njs_object_math_log(njs_vm_t *vm, njs_value_t *args, nxt_uint_t nargs, njs_index_t unused) @@ -551,6 +590,13 @@ static const njs_object_prop_t njs_math_object_properties[] = NJS_SKIP_ARG, NJS_NUMBER_ARG), }, + /* ES6. */ + { + .type = NJS_METHOD, + .name = njs_string("hypot"), + .value = njs_native_function(njs_object_math_hypot, 0, 0), + }, + { .type = NJS_METHOD, .name = njs_string("log"), diff --git a/njs/test/njs_unit_test.c b/njs/test/njs_unit_test.c index e5375a97..e84cf46b 100644 --- a/njs/test/njs_unit_test.c +++ b/njs/test/njs_unit_test.c @@ -5519,6 +5519,27 @@ static njs_unit_test_t njs_test[] = { nxt_string("Math.abs('abc')"), nxt_string("NaN") }, + { nxt_string("Math.hypot()"), + nxt_string("0") }, + + { nxt_string("Math.hypot(1, 2, 'abc')"), + nxt_string("NaN") }, + + { nxt_string("Math.hypot(1, NaN, 3)"), + nxt_string("NaN") }, + + { nxt_string("Math.hypot(1, NaN, -Infinity)"), + nxt_string("Infinity") }, + + { nxt_string("Math.hypot(-42)"), + nxt_string("42") }, + + { nxt_string("Math.hypot(8, -15)"), + nxt_string("17") }, + + { nxt_string("Math.hypot(3, -4, 12.0, '84', 132)"), + nxt_string("157") }, + { nxt_string("Math.max()"), nxt_string("-Infinity") }, -- 2.47.3