#Get all possibilities of a array of option-values object
7 messages · Page 1 of 1 (latest)
This seems like a tricky one.
type Input = {
name: string,
values: string[]
}
type Output = {
name: string,
value: string
}
const options: Input[] = [
{
name: "Couleur",
values: [ "Bleu", "Rouge", "Jaune" ]
},
{
name: "Taille",
values: [ "5cm", "10cm" ]
}
]
function fuzz(input: Input[]) {
if (input.length > 5)
throw Error('IDIOT!')
const output: Output[][] = [ [] ]
const buzz = (index = 0) => {
for (let i = 0; i < input[ index ].values.length; ++i) {
output[ output.length - 1 ].push({
name: input[ index ].name,
value: input[ index ].values[ i ]
})
if (input[ index + 1 ])
buzz(index + 1)
output.push(output[ output.length - 1 ].slice(0, -1))
}
}
buzz()
const length = output[0].length
return output.filter(array => array.length === length)
}
console.log(fuzz(options))
This is what I came up with. It does create more than you wanted, but at the very end filters out everything you don't want leaving only your desired result.
There may be a better way to do this, but at the moment, this is what my brain came up with.
type Input = {
name: string,
values: string[]
}
type Output = {
name: string,
value: string
}
const options: Input[] = [
{
name: "Couleur",
values: [ "Bleu", "Rouge", "Jaune" ]
},
{
name: "Taille",
values: [ "5cm", "10cm" ]
}
]
function fuzz(input: Input[]) {
if (input.length > 5)
throw Error('IDIOT!')
const output: Output[][] = [ [] ]
const buzz = (index = 0) => {
for (let i = 0; i < input[ index ].values.length; ++i) {
output[ output.length - 1 ].push({
name: input[ index ].name,
value: input[ index ].values[ i ]
})
if (input[ index + 1 ]) {
buzz(index + 1)
}
output.push(i < input[index].values.length - 1 ? output[ output.length - 1 ].slice(0, -1) : [])
}
}
buzz()
return output.filter(array => array.length)
}
console.log(fuzz(options))