Skip to content

Commit afd7f6e

Browse files
Created test and method to shuffle array.
1 parent 7b802c6 commit afd7f6e

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/Util.js

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export const shuffle = (list) => {
2+
const copy = [...list];
3+
let i = copy.length;
4+
let temp = null;
5+
let rI = null;
6+
7+
while (0 !== i) {
8+
rI = Math.floor(Math.random() * i);
9+
i--;
10+
temp = copy[i];
11+
copy[i] = copy[rI];
12+
copy[rI] = temp;
13+
}
14+
return copy;
15+
};

test/Util.test.js

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { shuffle } from '../src/Util';
2+
3+
describe('Tests for the shuffle util function.', () => {
4+
5+
test('Shuffle randomizes order in array.', () => {
6+
const array = ['a', 'b', 'c', 'd', 'e'];
7+
const shuffled = shuffle(array);
8+
expect(shuffled).toEqual(expect.arrayContaining(array));
9+
expect(JSON.stringify(shuffled)).not.toStrictEqual(JSON.stringify(array));
10+
});
11+
});

0 commit comments

Comments
 (0)