I have created a product configurator in VueJS and the whole functionality of it runs on one single function. I've put the word algoritm in the title in quotes because I don't really know if it is allowed that title. Anyhow, I have a feeling that the code I wrote is way to complicated and repeat a-lot of the same statements.
I honestly don't really know how to improve it to make it more efficient and readable. I read about something called DYI (Don't repeat yourself) which is actually a really good thought while programming. My thought is that I went too deep with the levels whilst it is not really necessary
How can I improve my code?
A little context: It regards a product configurator where a product has steps and each step has multiple options(Products). When clicked on a card the option should be added to the array. If the option is not in stock don't do anything at all and if the step allows multiple select. Append the option to the array anyway. If you read the comments I think it would make sense.
addToChosenOptions(step, option) {
// Option is in stock
if(option.stock === 1) {
// Check if the step where the option belongs to, exists in the array of ChosenOptions
if(this.chosenOptions.some(options => options[0].step.name === step.name)) {
// The step allows multiple select
if(step.allow_multiple) {
// The option exists in the array of selected options
if(this.optionExistInArray(option.name)){
// Loop through all the chosenOptions
this.chosenOptions.forEach(function(value, i) {
// The step equals the step given
if(value[0].step.name === step.name) {
// the options array length is 1 (Meaning its the last one in the array)
if (value[0].options.length === 1) {
// Delete the whole array instead of only the option
this.chosenOptions.splice(i, 1)
} else {
// The array's length is NOT 1 and thus only the options needs to be deleted
value[0].options.forEach(function(chOption, index) {
// If the option equals the option given
if(chOption.name === option.name) {
// Delete the option from the array
value[0].options.splice(index, 1);
}
});
}
}
}, this);
} else {
// If the option does not exists in the array
this.chosenOptions.forEach(function(value, i) {
// If the step name equals the given name
if(value[0].step.name === step.name) {
// Push the option to the right options array
value[0].options.push(option)
}
},this);
}
} else {
// If the stap does NOT allow for multiple select
this.chosenOptions.forEach(function(value, i) {
// If the step equals the given step
if(value[0].step.name === step.name) {
// Replace the current option with the new option
Vue.set(this.chosenOptions[i][0].options, 0, option)
}
}, this);
}
} else {
// If neither do exist at all in the array, Add the stap AND the option to the array
this.chosenOptions.push([{step: step, options: [option]}])
}
}
},
Thank you