I am currently working on implementing a strategic design pattern.
Here is a simple if-else ladder that I have:
if(dataKeyinresponse === 'year') {
bsd = new Date(moment(new Date(item['key'])).startOf('year').format('YYYY-MM-DD'))
nestedbed = new Date(moment(new Date(item['key'])).endOf('year').format('YYYY-MM-DD'));
} else if(dataKeyinresponse === 'quarter') {
let tempDate = new Date(moment(new Date(item['key'])).add(2, 'months').format('YYYY-MM-DD'));
// nestedbed = new Date(moment(new Date(item['key'])).add(3, 'months').format('YYYY-MM-DD'));
nestedbed = new Date(moment(tempDate).endOf('month').format('YYYY-MM-DD'));
} else if(dataKeyinresponse === 'month') {
nestedbed = new Date(moment(new Date(item['key'])).endOf('month').format('YYYY-MM-DD'));
} else if(dataKeyinresponse === 'week') {
//Relying more on the ES start date for week
nestedbed = new Date(moment(new Date(item['key'])).weekday(7).format('YYYY-MM-DD'));
} else {
// bed = bucketStartDate;
nestedbed = new Date(item['key']);
}
And now, I have applied the strategic pattern to it:
interface emptyBucketInterface {
fnGetEmptyBuckets();
}
class year implements emptyBucketInterface {
fnGetEmptyBuckets() {
bsd = new Date(moment(new Date(item['key'])).startOf('year').format('YYYY-MM-DD'))
nestedbed = new Date(moment(new Date(item['key'])).endOf('year').format('YYYY-MM-DD'));
return {
"bsd": bsd,
"nestedbed": nestedbed
};
}
}
class quarter implements emptyBucketInterface {
fnGetEmptyBuckets() {
let tempDate = new Date(moment(new Date(item['key'])).add(2, 'months').format('YYYY-MM-DD'));
nestedbed = new Date(moment(tempDate).endOf('month').format('YYYY-MM-DD'));
return {
"tempDate": tempDate,
"nestedbed": nestedbed
};
}
}
class month implements emptyBucketInterface {
fnGetEmptyBuckets() {
nestedbed = new Date(moment(new Date(item['key'])).endOf('month').format('YYYY-MM-DD'));
return {
"nestedbed": nestedbed
};
}
}
class week implements emptyBucketInterface {
fnGetEmptyBuckets() {
nestedbed = new Date(moment(new Date(item['key'])).weekday(7).format('YYYY-MM-DD'));
return {
"nestedbed": nestedbed
};
}
}
However, I'm uncertain about how to determine which class to invoke based on a condition.
In the previous if-else ladder, it checks for the value of dataKeyinresponse
and then executes certain statements.
But in the strategic pattern, I'm unsure how to evaluate the condition and then trigger the appropriate class.
Any assistance or guidance would be greatly appreciated.