Generating Product Variants
by kshep92
JavaScript
const colours = { name: 'Colour', values: ['Black', 'Brown', 'White', 'Moss'] };
const networks = { name: 'Network', values: ['Unlocked', 'bMobile', 'Digicel'] };
const capacities = { name: 'Capacity', values: ['64GB', '128GB', '256GB'] };
function createVariants(arr) {
let permutations;
arr.forEach(e => {
if(permutations == undefined) permutations = e.values.length;
else permutations *= e.values.length
});
console.log(`There are ${permutations} possible variations.`);
let variations = [];
for(let i=0; i < arr.length; i++) {
/* Some variables to store key properties of the current array element.*/
let currentElm = arr[i];
let property = currentElm.name;
let values = currentElm.values;
/* A place to store the modified versions of existing variations created in this run of the loop. */
let tmpVariations = [];
/* If there aren't any existing variations, then initialize the array. */
if(variations.length == 0) {
values.forEach(value => {
variations.push({[property]:value});
});
} else {
/* For each existing variation, add this [property] and one of its values to it.*/
variations.forEach(variation => {
values.forEach(value => {
let _var = {...variation, [property]:value};
tmpVariations.push(_var); // Store the modified variations in a temporary array.
});
variations = tmpVariations; // Replace the actual array with the array of updated variations.
});
}
}
console.log(`Created ${variations.length} variations: `);
console.log(variations);
}
createVariants([networks, capacities, colours]);