freeCodeCamp/shared/utils/shuffle-array.ts
Huyen Nguyen 0ba9eeff43
refactor(api, curriculum): use the shared shuffleArray util (#56444)
Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>
2024-10-02 08:55:38 -05:00

15 lines
477 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** Shuffle array using the FisherYates shuffle algorithm */
export const shuffleArray = <T>(arrToShuffle: Array<T>) => {
const arr = [...arrToShuffle];
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
// We know that i and j are within the bounds of the array, TS doesn't
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
[arr[i], arr[j]] = [arr[j]!, arr[i]!];
}
return arr;
};