I have this function, I am excluding some of the logic since it is not all relevant to my initial question. The main question is how I can optimise code to not be as repetitive. I was thinking to set them as variables to reuse but since the data is different it will not provide correct results. Any suggestions or examples that can point me in the right direction would be appreciated.
function myFunction() {
const checkOne = condition && condition
const checkTwo = condition && condition
if (checkOne || checkTwo) {
let someuniquestringone;
let someuniquestringtwo;
if (checkOne) {
...
const randomData = function({
moreData: 'STRING',
moreUniqueDataOne: moreUniqueDataOne,
});
someMethod(
insideFunction({
evenMoreData: evenMoreData,
evenMoreUniqueDataOne: 'someuniquestringone',
}),
);
}
if (checkTwo) {
...
const randomData = function({
moreData: 'STRING',
moreUniqueData: moreUniqueDataTwo,
});
someMethod(
insideFunction({
evenMoreData: evenMoreData,
evenMoreUniqueDataTwo: 'someuniquestringtwo',
}),
);
}
....
}
....
}
My main observation was that I can reuse this so it is not as repetitive:
const randomData = function({
moreData: 'STRING',
moreUniqueDataOne: moreUniqueDataOne,
});
someMethod(
insideFunction({
evenMoreData: evenMoreData,
evenMoreUniqueDataOne: 'someuniquestringone',
}),
);
You should group your conditions and data somehow to be able to associete them without hardcoding variables for each individually (moreUniqueData, someuniquestring). I'd suggest using a json array for that. Then you can just iterate over your array or filter out any condidtion that is not true. Something like that maybe:
function myFunction() {
//this the association array which connects conditions with their data and strings
const checks = [
{condition: condition && condition, string: someuniquestringone, moreUniqueData: {/* some data */}, evenMoreData: {/* some data */}},
{condition: condition && condition, string: someuniquestringtwo, moreUniqueData: {/* some data */}, evenMoreData: {/* some data */}}
/* maybe even more conditions and data */
}
/* find only the checks that are true, because others are not used in your code.
If none is true, the array of trueChecks will be empty and nothing is executed
*/
const trueChecks = checks.filter(check => {return check.condition === true});
//iterate over the true entries with their associeted data:
for (let check of trueChecks ) {
const randomData = {moreData: 'STRING', ...check.moreUniqueData};
someMethod(
insideFunction({
evenMoreData: check.evenMoreData,
evenMoreUniqueDataOne: check.string,
}),
);
}
....
}