about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2023-09-03 16:22:36 +0200
committerbptato <nincsnevem662@gmail.com>2023-09-03 16:25:41 +0200
commitb7367506fa05e9396e69b1db7277e011722af6b0 (patch)
tree5097114bb231dff851a47638e3230647010f546c
parent3f27d0807bd1f46d2b92d33759392c298592db20 (diff)
downloadchawan-b7367506fa05e9396e69b1db7277e011722af6b0.tar.gz
quickjs: add Array.prototype.at
-rw-r--r--lib/quickjs/quickjs.c30
1 files changed, 30 insertions, 0 deletions
diff --git a/lib/quickjs/quickjs.c b/lib/quickjs/quickjs.c
index 52f1d159..7aa3cfd2 100644
--- a/lib/quickjs/quickjs.c
+++ b/lib/quickjs/quickjs.c
@@ -38544,6 +38544,35 @@ exception:
     return JS_EXCEPTION;
 }
 
+static JSValue js_array_at(JSContext *ctx, JSValueConst this_val, int argc,
+                           JSValueConst *argv)
+{
+    JSValue obj, val;
+    int64_t len, k;
+
+    obj = JS_ToObject(ctx, this_val);
+    if (JS_IsException(obj))
+        return JS_EXCEPTION;
+
+    if (js_get_length64(ctx, &len, obj))
+        goto exception;
+
+    if (JS_ToInt64Clamp(ctx, &k, argv[0], -1, len, len))
+        goto exception;
+
+    if (k >= len || k < 0) {
+        JS_FreeValue(ctx, obj);
+        return JS_UNDEFINED;
+    }
+
+    val = JS_GetPropertyInt64(ctx, obj, k);
+    JS_FreeValue(ctx, obj);
+    return val;
+exception:
+    JS_FreeValue(ctx, obj);
+    return JS_EXCEPTION;
+}
+
 #define special_every    0
 #define special_some     1
 #define special_forEach  2
@@ -39840,6 +39869,7 @@ static const JSCFunctionListEntry js_iterator_proto_funcs[] = {
 
 static const JSCFunctionListEntry js_array_proto_funcs[] = {
     JS_CFUNC_DEF("concat", 1, js_array_concat ),
+    JS_CFUNC_DEF("at", 1, js_array_at ),
     JS_CFUNC_MAGIC_DEF("every", 1, js_array_every, special_every ),
     JS_CFUNC_MAGIC_DEF("some", 1, js_array_every, special_some ),
     JS_CFUNC_MAGIC_DEF("forEach", 1, js_array_every, special_forEach ),