Skip to content

Commit aeeba87

Browse files
committed
replace type for shuffle (and test it)
1 parent 62e2651 commit aeeba87

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

test/types/generics.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ function setup() {
1111

1212
// The types should fail if the result of random() is any
1313
logMessage(message);
14+
15+
testShuffleMaintainsType();
1416
}
1517

1618
// From: https://stackoverflow.com/a/50375286/62076
@@ -29,3 +31,23 @@ type NotAny<T> = IsStrictlyAny<T> extends true ? never : T
2931
function logMessage(message: NotAny<{ content: string }>) {
3032
console.log(message)
3133
}
34+
35+
36+
37+
/** test that shuffle(arr) preserves arr type in return, not just any[] */
38+
function testShuffleMaintainsType(){
39+
40+
type Expect<T extends true> = T;
41+
type Equal<X, Y> =
42+
(<T>() => T extends X ? 1 : 2) extends
43+
(<T>() => T extends Y ? 1 : 2) ? true : false;
44+
45+
const shuffleResult1 = shuffle(["a", "b", "c"]);
46+
const shuffleResult2 = shuffle(["a", 10, null]);
47+
//check the signature with the optional boolean type-checks, too
48+
const shuffleResult3 = shuffle([10, 20, 30], true);
49+
50+
type ShuffleTest1 = Expect<Equal<typeof shuffleResult1, string[]>>;
51+
type ShuffleTest2 = Expect<Equal<typeof shuffleResult2, (string|number|null)[]>>;
52+
type ShuffleTest3 = Expect<Equal<typeof shuffleResult3, number[]>>;
53+
}

utils/patch.mjs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,12 @@ export function applyPatches() {
4444
"random<T>(choices: readonly T[]): T;"
4545
);
4646

47+
replace(
48+
['p5.d.ts', 'global.d.ts'],
49+
'shuffle(array: any[], bool?: boolean): any[];',
50+
'shuffle<T>(array: T[], bool?: boolean): T[];'
51+
);
52+
4753
replace(
4854
'p5.d.ts',
4955
'textToContours(str: string, x: number, y: number, options?: { sampleFactor?: number; simplifyThreshold?: number }): object[][];',

0 commit comments

Comments
 (0)