Skip to content
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
1 change: 1 addition & 0 deletions src/LuaLib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { LuaTarget } from "./CompilerOptions";
import { getOrUpdate } from "./utils";

export enum LuaLibFeature {
ArrayAt = "ArrayAt",
ArrayConcat = "ArrayConcat",
ArrayEntries = "ArrayEntries",
ArrayEvery = "ArrayEvery",
Expand Down
13 changes: 13 additions & 0 deletions src/lualib/ArrayAt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.at
// Technically the specs also allow non-numeric types to be passed as index.
// However, TypeScript types the `Array.at` index param as number so we also expect only numbers
// This behaviour also matches the implementation of other Array functions in lualib.
export function __TS__ArrayAt<T>(this: T[], relativeIndex: number): T | undefined {
const absoluteIndex = relativeIndex < 0 ? this.length + relativeIndex : relativeIndex;

if (absoluteIndex >= 0 && absoluteIndex < this.length) {
return this[absoluteIndex];
}

return undefined;
}
2 changes: 2 additions & 0 deletions src/transformation/builtins/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ export function transformArrayPrototypeCall(

const expressionName = calledMethod.name.text;
switch (expressionName) {
case "at":
return transformLuaLibFunction(context, LuaLibFeature.ArrayAt, node, caller, ...params);
case "concat":
return transformLuaLibFunction(context, LuaLibFeature.ArrayConcat, node, caller, ...params);
case "entries":
Expand Down
30 changes: 30 additions & 0 deletions test/unit/builtins/array.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,36 @@ test("tuple.forEach", () => {
`.expectToMatchJsResult();
});

describe("at", () => {
test("valid index", () => {
util.testFunction`
const array = [1, 2, 3, 4];
return array.at(2);
`.expectToMatchJsResult();
});

test("invalid index", () => {
util.testFunction`
const array = [1, 2, 3, 4];
return array.at(10);
`.expectToMatchJsResult();
});

test("valid negative index", () => {
util.testFunction`
const array = [1, 2, 3, 4];
return array.at(-2);
`.expectToMatchJsResult();
});

test("invalid negative index", () => {
util.testFunction`
const array = [1, 2, 3, 4];
return array.at(-10);
`.expectToMatchJsResult();
});
});

test("array.forEach (%p)", () => {
util.testFunction`
const array = [0, 1, 2, 3];
Expand Down