-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcombine.js
48 lines (38 loc) · 1.22 KB
/
combine.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
// ==============================================
function combine(params) {
const keys = Object.keys(params);
return combineRecursive(keys, keys, 0, {}, params);
}
// ==============================================
function generateRange(from, to, step = 1) {
const range = [];
for (let i = from; i <= to; i += step) {
range.push(i);
}
return range;
}
// ==============================================
function combineRecursive(arrays, keys, index = 0, current = {}, params) {
if (index === arrays.length) {
return [current];
}
const result = [];
const key = keys[index];
const param = params[key];
if (typeof param !== 'object') {
const newCombination = { ...current, [key]: param };
return combineRecursive(arrays, keys, index + 1, newCombination, params);
}
let { from } = param;
const { to } = param;
const step = param.step || 1;
// one param depends on another
if (typeof from === 'string') from = current[from];
const range = generateRange(from, to, step);
range.forEach((value) => {
const newCombination = { ...current, [key]: value };
result.push(...combineRecursive(arrays, keys, index + 1, newCombination, params));
});
return result;
}
module.exports = combine;