I have a start period and end period selection which displays the result based on the start and end period. The function call is having redundant data. How can i improve it ? Also i have a bug in the code. In the edit form i am able to see the already saved start , end and payment days. When i change the start or end period already existing data is lost. Is there a better way to fix this as well?
<date-monthly
type=“text”
name=“start_period”
v-model=“startPeriod”
@on-change=“getStart”
required
>
<date-monthly
type=“text”
name=“end_period”
v-model=“endPeriod”
@on-change=“getEnd”
required
>
<script>
new Vue({
el: 'div#payment',
name: 'appPayment',
data: () => ({
startPeriod: @json(old('start_period', $paymentCalendar->start_period->format('Y-m-d'))),
endPeriod: @json(old('end_period', $paymentCalendar->end_period->format('Y-m-d'))),
paymentDays: @json(old('paymentDays', $paymentCalendar->paymentDays->keyBy('payment_period'))),
}),
methods: {
getStart(_, startDate){
let dateObj = {};
let currentDate = moment(startDate);
const endDate = moment(this.endPeriod);
while (currentDate <= endDate) {
dateObj[`${moment(currentDate).format('YYYY-MM-01')}`] = 0;
currentDate = moment(currentDate).add(1, 'days');
}
const output = Object.entries(dateObj).map(([payment_period]) => ({
payment_period,
}));
this.paymentDays = output;
},
getEnd(_, endDate) {
let dateObj = {};
let currentDate = moment(this.startPeriod);
const endDateTemp = moment(endDate);
while (currentDate <= endDateTemp) {
dateObj[`${moment(currentDate).format('YYYY-MM-01')}`] = 0;
currentDate = moment(currentDate).add(1, 'days');
}
const output = Object.entries(dateObj).map(([payment_period]) => ({
payment_period,
}));
this.paymentDays = output;
},
},
})
</script>
Note: the onchange of my custom date picker is having parameter as follows:
this.$emit(‘on-change’, $event, $date, $instance). So only the second param is date.
So is there a better way to remove the duplicate code in my getStart and getEnd functions?
Screenshot is as follows: