]> git.kaiwu.me - njs.git/commitdiff
Math.hypot() method.
authorValentin Bartenev <vbart@nginx.com>
Tue, 8 Nov 2016 19:09:40 +0000 (22:09 +0300)
committerValentin Bartenev <vbart@nginx.com>
Tue, 8 Nov 2016 19:09:40 +0000 (22:09 +0300)
njs/njs_math.c
njs/test/njs_unit_test.c

index 7b0297ee0e637c52d07e14fc499c16e750ee0f0a..c65a596ffd0dd27b2cc9fa4fa5a07946204d58e8 100644 (file)
@@ -19,6 +19,7 @@
 #include <njs_object.h>
 #include <njs_function.h>
 #include <math.h>
+#include <errno.h>
 
 
 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"),
index e5375a97f55db4747f3d06c8e9aa4b985be5eac2..e84cf46b874dfbef9c182a519c8e08efc4f613fb 100644 (file)
@@ -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") },