[njs] Introduced Array.prototype.toReversed().

Dmitry Volyntsev xeioex at nginx.com
Sat May 27 02:15:58 UTC 2023


details:   https://hg.nginx.org/njs/rev/e74e56120102
branches:  
changeset: 2137:e74e56120102
user:      Dmitry Volyntsev <xeioex at nginx.com>
date:      Fri May 26 19:13:41 2023 -0700
description:
Introduced Array.prototype.toReversed().

diffstat:

 src/njs_array.c          |  46 ++++++++++++++++++++++++++++++++++++++++++++++
 src/test/njs_unit_test.c |   3 +++
 2 files changed, 49 insertions(+), 0 deletions(-)

diffs (76 lines):

diff -r 76a8034b15e1 -r e74e56120102 src/njs_array.c
--- a/src/njs_array.c	Fri May 26 19:13:41 2023 -0700
+++ b/src/njs_array.c	Fri May 26 19:13:41 2023 -0700
@@ -1575,6 +1575,50 @@ njs_array_prototype_reverse(njs_vm_t *vm
 }
 
 
+static njs_int_t
+njs_array_prototype_to_reversed(njs_vm_t *vm, njs_value_t *args,
+    njs_uint_t nargs, njs_index_t unused, njs_value_t *retval)
+{
+    int64_t      length, i;
+    njs_int_t    ret;
+    njs_array_t  *array;
+    njs_value_t  *this, value;
+
+    this = njs_argument(args, 0);
+
+    ret = njs_value_to_object(vm, this);
+    if (njs_slow_path(ret != NJS_OK)) {
+        return ret;
+    }
+
+    ret = njs_value_length(vm, this, &length);
+    if (njs_slow_path(ret != NJS_OK)) {
+        return ret;
+    }
+
+    array = njs_array_alloc(vm, 0, length, 0);
+    if (njs_slow_path(array == NULL)) {
+        return NJS_ERROR;
+    }
+
+    njs_set_array(retval, array);
+
+    for (i = 0; i < length; i++) {
+        ret = njs_value_property_i64(vm, this, length - i - 1, &value);
+        if (njs_slow_path(ret == NJS_ERROR)) {
+            return NJS_ERROR;
+        }
+
+        ret = njs_value_create_data_prop_i64(vm, retval, i, &value, 0);
+        if (njs_slow_path(ret != NJS_OK)) {
+            return ret;
+        }
+    }
+
+    return NJS_OK;
+}
+
+
 njs_int_t
 njs_array_prototype_to_string(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,
     njs_index_t unused, njs_value_t *retval)
@@ -3189,6 +3233,8 @@ static const njs_object_prop_t  njs_arra
 
     NJS_DECLARE_PROP_NATIVE("splice", njs_array_prototype_splice, 2, 0),
 
+    NJS_DECLARE_PROP_NATIVE("toReversed", njs_array_prototype_to_reversed, 0, 0),
+
     NJS_DECLARE_PROP_NATIVE("toSorted", njs_array_prototype_to_sorted, 1, 0),
 
     NJS_DECLARE_PROP_NATIVE("toSpliced", njs_array_prototype_to_spliced, 2, 0),
diff -r 76a8034b15e1 -r e74e56120102 src/test/njs_unit_test.c
--- a/src/test/njs_unit_test.c	Fri May 26 19:13:41 2023 -0700
+++ b/src/test/njs_unit_test.c	Fri May 26 19:13:41 2023 -0700
@@ -5218,6 +5218,9 @@ static njs_unit_test_t  njs_test[] =
     { njs_str("Array.prototype[0] = 0; var x = [,1]; x.reverse(); x"),
       njs_str("1,0") },
 
+    { njs_str("var a = [,3,2,1]; njs.dump([a.toReversed(),a])"),
+      njs_str("[[1,2,3,undefined],[<empty>,3,2,1]]") },
+
     { njs_str("var a = [1,2,3,4]; a.indexOf()"),
       njs_str("-1") },
 


More information about the nginx-devel mailing list