Skip to content

Commit e420bfd

Browse files
authored
Merge pull request #122 from dsaxton/refactor-shuffle
Refactor __shuffle in utils.js
2 parents d8d58e6 + 412be2d commit e420bfd

2 files changed

Lines changed: 19 additions & 4 deletions

File tree

danfojs/src/core/utils.js

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -615,12 +615,11 @@ export class Utils {
615615

616616
__shuffle(num, array) {
617617
//https://stackoverflow.com/questions/18806210/generating-non-repeating-random-numbers-in-js/18806417
618-
var i = array.length,
619-
j = 0,
618+
var j,
620619
temp;
621620

622-
while (i--) {
623-
j = Math.floor(Math.random() * (i + 1));
621+
for (let i = 0; i < num; i++) {
622+
j = Math.floor(Math.random() * (array.length - i)) + i;
624623

625624
// swap randomly chosen element with current element
626625
temp = array[i];

danfojs/tests/core/utils.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,4 +217,20 @@ describe("Utils Functions", function () {
217217
});
218218
});
219219

220+
describe("__shuffle", function() {
221+
it("returns array with correct shape", function() {
222+
let data = [ 1, 2, 3, 4, 5 ];
223+
assert.deepEqual(utils.__shuffle(3, data).length, 3);
224+
});
225+
226+
it("returns original values when num equals total length", function() {
227+
let data = [ 1, 2, 3, 4, 5 ];
228+
assert.deepEqual(utils.__shuffle(5, data).sort(), [ 1, 2, 3, 4, 5 ]);
229+
});
230+
231+
it("returns empty array when num equals zero", function() {
232+
let data = [ 1, 2, 3, 4, 5 ];
233+
assert.deepEqual(utils.__shuffle(0, data), []);
234+
});
235+
});
220236
});

0 commit comments

Comments
 (0)