Skip to content

Commit 6b5ccbd

Browse files
committed
feat: added byRandom()
1 parent 05f5448 commit 6b5ccbd

2 files changed

Lines changed: 21 additions & 0 deletions

File tree

src/sort/byRandom.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
/**
2+
* Randomly return -1, 0, or 1. This is an easy way to shuffle an array.
3+
*/
4+
export const byRandom = (): number => (crypto.getRandomValues(new Uint8Array(1))[0]! % 3) - 1;

test/sort/byRandom.test.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { describe, expect, it } from 'vitest';
2+
3+
import { byRandom } from '../../src/sort/byRandom.js';
4+
5+
describe('byRandom', () => {
6+
it('should sort items randomly', () => {
7+
expect(byRandom()).toBeOneOf([-1, 0, 1]);
8+
});
9+
10+
it('can be used to shuffle an array', () => {
11+
const data = [1, 2, 3, 4, 5];
12+
const shuffledData = data.toSorted(byRandom);
13+
14+
expect(shuffledData).toHaveLength(data.length);
15+
expect(shuffledData).toEqual(expect.arrayContaining(data));
16+
});
17+
});

0 commit comments

Comments
 (0)