From 99eb81e1a65cfaee5c2a99025e7c512895d3b281 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Sun, 5 Nov 2023 11:08:46 +0100 Subject: [PATCH] Implement Array.prototype.at (#13) --- quickjs.c | 33 +++++++++++++++++++++++++++++++++ test262.conf | 2 +- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/quickjs.c b/quickjs.c index 3edd140..53ce7ca 100644 --- a/quickjs.c +++ b/quickjs.c @@ -38412,6 +38412,38 @@ static int JS_isConcatSpreadable(JSContext *ctx, JSValueConst obj) return JS_IsArray(ctx, obj); } +static JSValue js_array_at(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv) +{ + JSValue obj, ret; + int64_t len, idx; + JSValue *arrp; + uint32_t count; + + ret = JS_EXCEPTION; + obj = JS_ToObject(ctx, this_val); + if (js_get_length64(ctx, &len, obj)) + goto exception; + + if (JS_ToInt64Sat(ctx, &idx, argv[0])) + goto exception; + + if (idx < 0) + idx = len + idx; + + if (idx < 0 || idx >= len) { + ret = JS_UNDEFINED; + } else if (js_get_fast_array(ctx, obj, &arrp, &count) && count == len) { + ret = JS_DupValue(ctx, arrp[idx]); + } else if (!JS_TryGetPropertyInt64(ctx, obj, idx, &ret)) { + ret = JS_UNDEFINED; + } + + exception: + JS_FreeValue(ctx, obj); + return ret; +} + static JSValue js_array_concat(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { @@ -39773,6 +39805,7 @@ static const JSCFunctionListEntry js_iterator_proto_funcs[] = { }; static const JSCFunctionListEntry js_array_proto_funcs[] = { + JS_CFUNC_DEF("at", 1, js_array_at ), JS_CFUNC_DEF("concat", 1, js_array_concat ), JS_CFUNC_MAGIC_DEF("every", 1, js_array_every, special_every ), JS_CFUNC_MAGIC_DEF("some", 1, js_array_every, special_some ), diff --git a/test262.conf b/test262.conf index 3f39cfc..6a7e9b9 100644 --- a/test262.conf +++ b/test262.conf @@ -58,7 +58,7 @@ arbitrary-module-namespace-names=skip array-find-from-last=skip array-grouping=skip Array.fromAsync=skip -Array.prototype.at=skip +Array.prototype.at Array.prototype.flat Array.prototype.flatMap Array.prototype.flatten