diff --git a/src/utilities/utility_functions.js b/src/utilities/utility_functions.js index 00e2c462b8..8125639e6f 100644 --- a/src/utilities/utility_functions.js +++ b/src/utilities/utility_functions.js @@ -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 @@ -759,9 +759,9 @@ function utilityFunctions(p5, fn){ * * */ - 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, diff --git a/test/types/generics.ts b/test/types/generics.ts index a86846e3f4..f59f575863 100644 --- a/test/types/generics.ts +++ b/test/types/generics.ts @@ -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 @@ -29,3 +31,23 @@ type NotAny = IsStrictlyAny 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; + type Equal = + (() => T extends X ? 1 : 2) extends + (() => 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>; + type ShuffleTest2 = Expect>; + type ShuffleTest3 = Expect>; +} diff --git a/utils/patch.mjs b/utils/patch.mjs index 0d6e2a0bec..446a6ef755 100644 --- a/utils/patch.mjs +++ b/utils/patch.mjs @@ -44,6 +44,12 @@ export function applyPatches() { "random(choices: readonly T[]): T;" ); + replace( + ['p5.d.ts', 'global.d.ts'], + 'shuffle(array: any[], modify?: boolean): any[];', + 'shuffle(array: T[], modify?: boolean): T[];' + ); + replace( 'p5.d.ts', 'textToContours(str: string, x: number, y: number, options?: { sampleFactor?: number; simplifyThreshold?: number }): object[][];',