[njs] Math.sign() method.

Valentin Bartenev vbart at nginx.com
Mon Oct 31 13:29:22 UTC 2016


details:   http://hg.nginx.org/njs/rev/d7a10c0dfcce
branches:  
changeset: 233:d7a10c0dfcce
user:      Valentin Bartenev <vbart at nginx.com>
date:      Mon Oct 31 16:28:12 2016 +0300
description:
Math.sign() method.

diffstat:

 njs/njs_math.c           |  31 +++++++++++++++++++++++++++++++
 njs/test/njs_unit_test.c |  18 ++++++++++++++++++
 2 files changed, 49 insertions(+), 0 deletions(-)

diffs (76 lines):

diff -r 1f68ffabcea9 -r d7a10c0dfcce njs/njs_math.c
--- a/njs/njs_math.c	Mon Oct 31 16:25:54 2016 +0300
+++ b/njs/njs_math.c	Mon Oct 31 16:28:12 2016 +0300
@@ -334,6 +334,29 @@ njs_object_math_round(njs_vm_t *vm, njs_
 
 
 static njs_ret_t
+njs_object_math_sign(njs_vm_t *vm, njs_value_t *args, nxt_uint_t nargs,
+    njs_index_t unused)
+{
+    double  num;
+
+    if (nargs > 1) {
+        num = args[1].data.u.number;
+
+        if (!njs_is_nan(num) && num != 0) {
+            num = signbit(num) ? -1 : 1;
+        }
+
+    } else {
+        num = NJS_NAN;
+    }
+
+    njs_number_set(&vm->retval, num);
+
+    return NXT_OK;
+}
+
+
+static njs_ret_t
 njs_object_math_sin(njs_vm_t *vm, njs_value_t *args, nxt_uint_t nargs,
     njs_index_t unused)
 {
@@ -567,6 +590,14 @@ static const njs_object_prop_t  njs_math
                      NJS_SKIP_ARG, NJS_NUMBER_ARG),
     },
 
+    /* ES6. */
+    {
+        .type = NJS_METHOD,
+        .name = njs_string("sign"),
+        .value = njs_native_function(njs_object_math_sign, 0,
+                     NJS_SKIP_ARG, NJS_NUMBER_ARG),
+    },
+
     {
         .type = NJS_METHOD,
         .name = njs_string("sin"),
diff -r 1f68ffabcea9 -r d7a10c0dfcce njs/test/njs_unit_test.c
--- a/njs/test/njs_unit_test.c	Mon Oct 31 16:25:54 2016 +0300
+++ b/njs/test/njs_unit_test.c	Mon Oct 31 16:28:12 2016 +0300
@@ -5373,6 +5373,24 @@ static njs_unit_test_t  njs_test[] =
     { nxt_string("Math.pow()"),
       nxt_string("NaN") },
 
+    { nxt_string("Math.sign(5)"),
+      nxt_string("1") },
+
+    { nxt_string("Math.sign(-5)"),
+      nxt_string("-1") },
+
+    { nxt_string("Math.sign(0)"),
+      nxt_string("0") },
+
+    { nxt_string("Math.sign(-0.0)"),
+      nxt_string("-0") },
+
+    { nxt_string("Math.sign(NaN)"),
+      nxt_string("NaN") },
+
+    { nxt_string("Math.sign()"),
+      nxt_string("NaN") },
+
     { nxt_string("Math.trunc(3.9)"),
       nxt_string("3") },
 



More information about the nginx-devel mailing list