]> git.kaiwu.me - njs.git/commitdiff
Math.trunc() method.
authorValentin Bartenev <vbart@nginx.com>
Mon, 31 Oct 2016 13:25:54 +0000 (16:25 +0300)
committerValentin Bartenev <vbart@nginx.com>
Mon, 31 Oct 2016 13:25:54 +0000 (16:25 +0300)
njs/njs_math.c
njs/test/njs_unit_test.c

index 42fbdb33330f9ba26af46e9b0f080702a858664d..72729975d4ac01057c6a1f2147d0a2722453f6d9 100644 (file)
@@ -390,6 +390,25 @@ njs_object_math_tan(njs_vm_t *vm, njs_value_t *args, nxt_uint_t nargs,
 }
 
 
+static njs_ret_t
+njs_object_math_trunc(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;
+
+    } else {
+        num = NJS_NAN;
+    }
+
+    njs_number_set(&vm->retval, trunc(num));
+
+    return NXT_OK;
+}
+
+
 static const njs_object_prop_t  njs_math_object_properties[] =
 {
     {
@@ -568,6 +587,14 @@ static const njs_object_prop_t  njs_math_object_properties[] =
         .value = njs_native_function(njs_object_math_tan, 0,
                      NJS_SKIP_ARG, NJS_NUMBER_ARG),
     },
+
+    /* ES6. */
+    {
+        .type = NJS_METHOD,
+        .name = njs_string("trunc"),
+        .value = njs_native_function(njs_object_math_trunc, 0,
+                     NJS_SKIP_ARG, NJS_NUMBER_ARG),
+    },
 };
 
 
index ae73d240c06da77c7edbd4d8ef72813aab6c92ef..c0f4cf9e0b5f61244391781004296a91dd3c731c 100644 (file)
@@ -5373,6 +5373,36 @@ static njs_unit_test_t  njs_test[] =
     { nxt_string("Math.pow()"),
       nxt_string("NaN") },
 
+    { nxt_string("Math.trunc(3.9)"),
+      nxt_string("3") },
+
+    { nxt_string("Math.trunc(-3.9)"),
+      nxt_string("-3") },
+
+    { nxt_string("Math.trunc(0)"),
+      nxt_string("0") },
+
+    { nxt_string("Math.trunc(-0)"),
+      nxt_string("-0") },
+
+    { nxt_string("Math.trunc(0.9)"),
+      nxt_string("0") },
+
+    { nxt_string("Math.trunc(-0.9)"),
+      nxt_string("-0") },
+
+    { nxt_string("Math.trunc(Infinity)"),
+      nxt_string("Infinity") },
+
+    { nxt_string("Math.trunc(-Infinity)"),
+      nxt_string("-Infinity") },
+
+    { nxt_string("Math.trunc(NaN)"),
+      nxt_string("NaN") },
+
+    { nxt_string("Math.trunc()"),
+      nxt_string("NaN") },
+
     /* ES5FIX: "[object Math]". */
 
     { nxt_string("Math"),