[njs] Math.hypot() method.
Valentin Bartenev
vbart at nginx.com
Wed Nov 9 09:59:26 UTC 2016
details: http://hg.nginx.org/njs/rev/8e800470d756
branches:
changeset: 243:8e800470d756
user: Valentin Bartenev <vbart at nginx.com>
date: Tue Nov 08 22:09:40 2016 +0300
description:
Math.hypot() method.
diffstat:
njs/njs_math.c | 46 ++++++++++++++++++++++++++++++++++++++++++++++
njs/test/njs_unit_test.c | 21 +++++++++++++++++++++
2 files changed, 67 insertions(+), 0 deletions(-)
diffs (101 lines):
diff -r cfd1e7ae9a07 -r 8e800470d756 njs/njs_math.c
--- a/njs/njs_math.c Wed Nov 09 12:37:59 2016 +0300
+++ b/njs/njs_math.c Tue Nov 08 22:09:40 2016 +0300
@@ -19,6 +19,7 @@
#include <njs_object.h>
#include <njs_function.h>
#include <math.h>
+#include <errno.h>
static njs_ret_t
@@ -197,6 +198,44 @@ njs_object_math_floor(njs_vm_t *vm, njs_
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
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 -r cfd1e7ae9a07 -r 8e800470d756 njs/test/njs_unit_test.c
--- a/njs/test/njs_unit_test.c Wed Nov 09 12:37:59 2016 +0300
+++ b/njs/test/njs_unit_test.c Tue Nov 08 22:09:40 2016 +0300
@@ -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") },
More information about the nginx-devel
mailing list