Skip to content

Commit 4ef4aa1

Browse files
committed
Fix array.sort compare function not working
1 parent 777d62c commit 4ef4aa1

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

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: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,22 @@ export class LuaLibTests
352352
// Assert
353353
Expect(result).toBe(JSON.stringify(expected));
354354
}
355+
356+
@TestCase("[4, 5, 3, 2, 1]", [1, 2, 3, 4, 5], "a - b")
357+
@TestCase('["4", "5", "3", "2", "1"]', ["1", "2", "3", "4", "5"], "tonumber(a) - tonumber(b)")
358+
@TestCase('["4", "5", "3", "2", "1"]', ["5", "4", "3", "2", "1"], "tonumber(b) - tonumber(a)")
359+
@Test("array.sort with compare function")
360+
public arraySortWithCompareFunction(array: string, expected: any, compare: string): void
361+
{
362+
const result = util.transpileAndExecute(
363+
`let testArray = ${array};
364+
testArray.sort((a, b) => ${compare});
365+
return JSONStringify(testArray)`);
366+
367+
// Assert
368+
Expect(result).toBe(JSON.stringify(expected));
369+
}
370+
355371
@TestCase("true", "4", "5", 4)
356372
@TestCase("false", "4", "5", 5)
357373
@TestCase("3", "4", "5", 4)

0 commit comments

Comments
 (0)