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
6 changes: 3 additions & 3 deletions src/utilities/utility_functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -676,7 +676,7 @@ function utilityFunctions(p5, fn){
*
* @method shuffle
* @param {Array} array array to shuffle.
* @param {Boolean} [bool] if `true`, shuffle the original array in place. Defaults to `false`.
* @param {Boolean} [modify] if `true`, shuffle the original array in place. Defaults to `false`.
* @return {Array} shuffled array.
*
* @example
Expand Down Expand Up @@ -759,9 +759,9 @@ function utilityFunctions(p5, fn){
* </code>
* </div>
*/
fn.shuffle = function (arr, bool) {
fn.shuffle = function (arr, modify) {
const isView = ArrayBuffer && ArrayBuffer.isView && ArrayBuffer.isView(arr);
arr = bool || isView ? arr : arr.slice();
arr = modify || isView ? arr : arr.slice();

let rnd,
tmp,
Expand Down
22 changes: 22 additions & 0 deletions test/types/generics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ function setup() {

// The types should fail if the result of random() is any
logMessage(message);

testShuffleMaintainsType();
}

// From: https://stackoverflow.com/a/50375286/62076
Expand All @@ -29,3 +31,23 @@ type NotAny<T> = IsStrictlyAny<T> extends true ? never : T
function logMessage(message: NotAny<{ content: string }>) {
console.log(message)
}



/** test that shuffle(arr) preserves arr type in return, not just any[] */
function testShuffleMaintainsType(){

type Expect<T extends true> = T;
type Equal<X, Y> =
(<T>() => T extends X ? 1 : 2) extends
(<T>() => T extends Y ? 1 : 2) ? true : false;

const shuffleResult1 = shuffle(["a", "b", "c"]);
const shuffleResult2 = shuffle(["a", 10, null]);
//check the signature with the optional boolean type-checks, too
const shuffleResult3 = shuffle([10, 20, 30], true);

type ShuffleTest1 = Expect<Equal<typeof shuffleResult1, string[]>>;
type ShuffleTest2 = Expect<Equal<typeof shuffleResult2, (string|number|null)[]>>;
type ShuffleTest3 = Expect<Equal<typeof shuffleResult3, number[]>>;
}
6 changes: 6 additions & 0 deletions utils/patch.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ export function applyPatches() {
"random<T>(choices: readonly T[]): T;"
);

replace(
['p5.d.ts', 'global.d.ts'],
'shuffle(array: any[], modify?: boolean): any[];',
'shuffle<T>(array: T[], modify?: boolean): T[];'
);

replace(
'p5.d.ts',
'textToContours(str: string, x: number, y: number, options?: { sampleFactor?: number; simplifyThreshold?: number }): object[][];',
Expand Down
Loading