Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement String.prototype.at #12

Merged
merged 1 commit into from
Nov 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions quickjs.c
Original file line number Diff line number Diff line change
Expand Up @@ -40441,6 +40441,36 @@ static JSValue js_string___isSpace(JSContext *ctx, JSValueConst this_val,
}
#endif

static JSValue js_string_at(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
JSValue val, ret;
JSString *p;
int idx, c;

val = JS_ToStringCheckObject(ctx, this_val);
if (JS_IsException(val))
return val;
p = JS_VALUE_GET_STRING(val);
if (JS_ToInt32Sat(ctx, &idx, argv[0])) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In case you're wondering why this works without checking argc > 0: this function is called by js_call_c_function() and that function ensures there are at least cfunc.length slots in the argv array, all set to JS_UNDEFINED.

JS_FreeValue(ctx, val);
return JS_EXCEPTION;
}
if (idx < 0)
idx = p->len + idx;
if (idx < 0 || idx >= p->len) {
ret = JS_UNDEFINED;
} else {
if (p->is_wide_char)
c = p->u.str16[idx];
else
c = p->u.str8[idx];
ret = js_new_string_char(ctx, c);
}
JS_FreeValue(ctx, val);
return ret;
}

static JSValue js_string_charCodeAt(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
Expand Down Expand Up @@ -41744,6 +41774,7 @@ static const JSCFunctionListEntry js_string_funcs[] = {

static const JSCFunctionListEntry js_string_proto_funcs[] = {
JS_PROP_INT32_DEF("length", 0, JS_PROP_CONFIGURABLE ),
JS_CFUNC_DEF("at", 1, js_string_at ),
JS_CFUNC_DEF("charCodeAt", 1, js_string_charCodeAt ),
JS_CFUNC_DEF("charAt", 1, js_string_charAt ),
JS_CFUNC_DEF("concat", 1, js_string_concat ),
Expand Down
2 changes: 1 addition & 1 deletion test262.conf
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ ShadowRealm=skip
SharedArrayBuffer
string-trimming
String.fromCodePoint
String.prototype.at=skip
String.prototype.at
String.prototype.endsWith
String.prototype.includes
String.prototype.isWellFormed=skip
Expand Down