I have following 2 dimensional array input:
var arr = [
['A', ['Sun','Moon']],
['B', ['Cat','Dog']],
['C', ['John','Peter','Zora']]
];
Using that input, I want all combinations applied to a given pattern in javascript:
The placeholders in the pattern are in following format: $(name)
Here are some sample patterns with result:
var pattern1 = "$(A) / $(A)";
/* Expected Result
"Sun / Sun"
"Sun / Moon"
"Moon / Sun"
"Moon / Moon"
*/
var pattern2 = "$(A)--$(B)";
/* Expected Result
"Sun--Cat"
"Sun--Dog"
"Moon--Cat"
"Moon--Dog"
*/
var pattern3 = "$(C) + $(B)";
/* Expected Result
"John + Cat"
"John + Dog"
"Peter + Cat"
"Peter + Dog"
"Zora + Cat"
"Zora + Dog"
*/
var pattern4 = "$(A) - $(A) * ( $(B) + $(C) )";
/* Expected Result
"Sun - Sun * ( Cat + John )"
"Sun - Sun * ( Cat + Peter )"
"Sun - Sun * ( Cat + Zora )"
"Sun - Sun * ( Dog + John )"
"Sun - Sun * ( Dog + Peter )"
"Sun - Sun * ( Dog + Zora )"
"Sun - Moon * ( Cat + John )"
"Sun - Moon * ( Cat + Peter )"
"Sun - Moon * ( Cat + Zora )"
"Sun - Moon * ( Dog + John )"
"Sun - Moon * ( Dog + Peter )"
"Sun - Moon * ( Dog + Zora )"
"Moon - Sun * ( Cat + John )"
"Moon - Sun * ( Cat + Peter )"
"Moon - Sun * ( Cat + Zora )"
"Moon - Sun * ( Dog + John )"
"Moon - Sun * ( Dog + Peter )"
"Moon - Sun * ( Dog + Zora )"
"Moon - Moon * ( Cat + John )"
"Moon - Moon * ( Cat + Peter )"
"Moon - Moon * ( Cat + Zora )"
"Moon - Moon * ( Dog + John )"
"Moon - Moon * ( Dog + Peter )"
"Moon - Moon * ( Dog + Zora )"
*/
The pattern can be any combination (with repeating placeholders) and any length.
Can someone help me with an algorithm in javascript?
Thank you.
You can use a recursive function to do this.
First you have to extract the names from the string. You can do this with a regular expression:
Then you pass this list plus a mapping of your values to a function which iterates over the names recursively:
This requires that your data structure will be an object:
Then you call the function with
DEMO