Let’s say I have an object specifying inputs for a button component, and the possible values of that input.
const buttonVariants = {
colorMode: ['on-dark','on-light'],
size: ['small','medium','large']
};
How could I create a cartesian function to generate templates for all possible combinations of the variants? I’d like to be able to re-use this function for multiple components, so it’s important to specify that I’d need this to work for n
variants.
I’m hoping to achieve something like this but where the output would be:
[
'<button colorMode="on-dark" size="small">button</button>',
'<button colorMode="on-dark" size="medium">button</button>',
'<button colorMode="on-dark" size="large">button</button>',
'<button colorMode="on-light" size="small">button</button>',
'<button colorMode="on-light" size="medium">button</button>',
'<button colorMode="on-light" size="large">button</button>'
]
2
Answers
You can use
Array::flatMap()
to map all color/size combinations:You can achieve this by first creating a generic function to generate the Cartesian product of multiple arrays. This function will be useful for generating all possible combinations of the variants you have. Then, you can map these combinations to generate the desired button templates. Let’s implement this in JavaScript:
By running this code, you will get the output in the format you specified, allowing you to generate templates for all possible combinations of the variants. This approach is flexible and can be reused for any number of variants and options.