Skip to content

Commit 10002b5

Browse files
ark120202Perryvw
authored andcommitted
Fix array.sort compare function not working (#458)
* Fix array.sort compare function not working * Fix compare function not being passed * Change array.sort tests to compare with js results
1 parent 777d62c commit 10002b5

File tree

3 files changed

+30
-3
lines changed

3 files changed

+30
-3
lines changed

src/LuaTransformer.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3715,7 +3715,7 @@ export class LuaTransformer {
37153715
case "unshift":
37163716
return this.transformLuaLibFunction(LuaLibFeature.ArrayUnshift, node, caller, ...params);
37173717
case "sort":
3718-
return this.transformLuaLibFunction(LuaLibFeature.ArraySort, node, caller);
3718+
return this.transformLuaLibFunction(LuaLibFeature.ArraySort, node, caller, ...params);
37193719
case "pop":
37203720
return tstl.createCallExpression(
37213721
tstl.createTableIndexExpression(tstl.createIdentifier("table"), tstl.createStringLiteral("remove")),

src/lualib/ArraySort.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
declare namespace table {
2-
function sort<T>(arr: T[], compareFn?: (a: T, b: T) => number): void;
2+
function sort<T>(arr: T[], compareFn?: (a: T, b: T) => boolean): void;
33
}
44
function __TS__ArraySort<T>(arr: T[], compareFn?: (a: T, b: T) => number): T[] {
5-
table.sort(arr, compareFn);
5+
if (compareFn !== undefined) {
6+
table.sort(arr, (a, b) => compareFn(a, b) < 0);
7+
} else {
8+
table.sort(arr);
9+
}
610
return arr;
711
}

test/unit/lualib/lualib.spec.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,29 @@ export class LuaLibTests
352352
// Assert
353353
Expect(result).toBe(JSON.stringify(expected));
354354
}
355+
356+
@Test("array.sort with compare function")
357+
@TestCase([1, 2, 3, 4, 5], "a - b", (a: number, b: number) => a - b)
358+
@TestCase(["4", "5", "3", "2", "1"], "tonumber(a) - tonumber(b)", (a: string, b: string) => Number(a) - Number(b))
359+
@TestCase(["4", "5", "3", "2", "1"], "tonumber(b) - tonumber(a)", (a: string, b: string) => Number(b) - Number(a))
360+
public arraySortWithCompareFunction(
361+
array: any[],
362+
compareStr: string,
363+
compareFn: (a: any, b: any) => number
364+
): void {
365+
const result = util.transpileAndExecute(
366+
`let testArray = ${JSON.stringify(array)};
367+
testArray.sort((a, b) => ${compareStr});
368+
return JSONStringify(testArray)`,
369+
undefined,
370+
undefined,
371+
`declare function tonumber(e: any): number`
372+
);
373+
374+
// Assert
375+
Expect(result).toBe(JSON.stringify(array.sort(compareFn)));
376+
}
377+
355378
@TestCase("true", "4", "5", 4)
356379
@TestCase("false", "4", "5", 5)
357380
@TestCase("3", "4", "5", 4)

0 commit comments

Comments
 (0)