Skip to content

Commit

Permalink
add arr.shuffle
Browse files Browse the repository at this point in the history
  • Loading branch information
ajmnz committed Jun 28, 2024
1 parent 57a6357 commit db81f61
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,23 @@ export const findOrThrow = <T extends unknown[]>(
}
return match;
};

/**
* Shuffle items inside an array.
*
* @param array - The array to shuffle
* @returns A new array with the items shuffled
* @example
* ```ts
* arr.shuffle([1, 2, 3, 4]); // [3, 1, 2, 4]
* ```
*/
export const shuffle = <T extends any[]>(array: T): T => {
const shuffled = [...array] as T;
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}

return shuffled;
};
16 changes: 16 additions & 0 deletions test/arr.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,20 @@ describe("arr", () => {
"foo"
);
});

test("shuffle", () => {
const array = [1, 2, 3, 4];

expect(arr.shuffle(array).length).toBe(array.length);
expect(arr.shuffle(array).sort()).toEqual([...array].sort());
expect(arr.shuffle(array)).not.toBe(array);

const shuffledResults = new Set<string>();
for (let i = 0; i < 100; i++) {
shuffledResults.add(arr.shuffle(array).toString());
}
expect(shuffledResults.size).toBeGreaterThan(1);
expect(arr.shuffle([])).toEqual([]);
expect(arr.shuffle([1])).toEqual([1]);
});
});

0 comments on commit db81f61

Please sign in to comment.