I'm using code adapted from this Stack Overflow question to calculate all possible combinations from an array, which may contains strings.
For example:
[ "x", "y", "z" ] => "x y z" [ [ "a", "b"] , "c", "d" ] => [ "a c d", "b c d" ] [ [ "a", "b"] , ["c" "d"], "e"] => [ "a c e", "b c e", "a d e", "b d e" ]
However as the items could be strings or array I need to check for all possible combinations of array/string pairs when building the results.
This has ended in rather messy code, and I'd appreciate any hints on how to tidy it up. I've attempted to refactor it, but I guess I'm tired and missing something!
function allPossibleCases(arr) {
if (arr.length === 0) {
return [];
}
else if (arr.length === 1){
return arr[0];
}
else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array
if(typeof allCasesOfRest === 'string') {
if(typeof arr[0] === 'string') {
result.push(arr[0] + " " + allCasesOfRest);
} else {
for (var i = 0; i < arr[0].length; i++) {
result.push(arr[0][i] + " " + allCasesOfRest);
}
}
}
else {
for (var c in allCasesOfRest) {
if(typeof arr[0] === 'string') {
result.push(arr[0] + " " + allCasesOfRest[c]);
} else {
for (var i = 0; i < arr[0].length; i++) {
result.push(arr[0][i] + " " + allCasesOfRest[c]);
}
}
}
}
return result;
}
}