-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
49 lines (38 loc) · 1010 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
'use strict';
const shuffle = require('knuth-shuffle');
const knuthShuffle = shuffle.knuthShuffle;
module.exports = (arrays) => {
if (!arrays.length) {
throw new Error('not arrays');
}
if (!arrays[0].length) {
throw new Error('array is empty');
}
const lengths = arrays.map(array => array.length);
const size = lengths.pop();
if (!areSameSize(lengths, size)) {
throw new Error('arrays are not same size');
}
const indexes = Array(size).fill().map((v, k) => k);
const shuffledIndexes = knuthShuffle(indexes);
return arrays.map(array => {
return array.reduce((result, value, key) => {
result[shuffledIndexes[key]] = value;
return result;
}, []);
});
}
function areSameSize(lengths, initSize) {
let isSameSize = true;
while (lengths.length) {
if (!isSameSize) {
return isSameSize;
}
if (initSize !== lengths[lengths.length - 1]) {
isSameSize = false;
} else {
lengths.pop();
}
}
return isSameSize;
}