@@ -34,12 +34,15 @@ export const calculateDateNextPurchased = (currentDate, item) => {
3434 item . dateNextPurchased ,
3535 item . dateLastPurchased ,
3636 ) ;
37- const estimatedNextPurchaseDate = getNextPurchaseEstimate (
37+ const { estimatedDaysUntilPurchase, nextPurchaseEstimate } =
38+ getNextPurchaseEstimate ( purchaseIntervals , item . totalPurchases + 1 ) ;
39+
40+ const averagePurchaseInterval = getAveragePurchaseInterval (
3841 purchaseIntervals ,
39- item . totalPurchases + 1 ,
40- ) ;
42+ estimatedDaysUntilPurchase ,
43+ ) . toFixed ( 1 ) ;
4144
42- return estimatedNextPurchaseDate ;
45+ return { nextPurchaseEstimate , averagePurchaseInterval } ;
4346 } catch ( error ) {
4447 throw new Error ( `Failed getting next purchase date: ${ error } ` ) ;
4548 }
@@ -120,8 +123,38 @@ function getNextPurchaseEstimate(purchaseIntervals, totalPurchases) {
120123
121124 const nextPurchaseEstimate = addDaysFromToday ( estimatedDaysUntilPurchase ) ;
122125
123- return nextPurchaseEstimate ;
126+ return { estimatedDaysUntilPurchase , nextPurchaseEstimate } ;
124127 } catch ( error ) {
125128 throw new Error ( `Failed updaing date next purchased: ${ error } ` ) ;
126129 }
127130}
131+
132+ /**
133+ * Calculates the average purchase interval based on known purchase intervals.
134+ *
135+ * This function takes into account the last estimated purchase interval,
136+ * the number of days since the last purchase, and the estimated days until the next purchase.
137+ * It computes the average of these intervals by summing them up and dividing by the total count.
138+ *
139+ * @param {Object } purchaseIntervals - An object containing the purchase interval data.
140+ * @param {number } purchaseIntervals.lastEstimatedInterval - The last estimated interval in days.
141+ * @param {number } purchaseIntervals.daysSinceLastPurchase - The number of days since the last purchase.
142+ * @param {number } estimatedDaysUntilPurchase - The estimated number of days until the next purchase.
143+ * @returns {number } The average purchase interval calculated from the provided intervals.
144+ */
145+ function getAveragePurchaseInterval (
146+ purchaseIntervals ,
147+ estimatedDaysUntilPurchase ,
148+ ) {
149+ const { lastEstimatedInterval, daysSinceLastPurchase } = purchaseIntervals ;
150+ const knownIntervals = [
151+ lastEstimatedInterval ,
152+ daysSinceLastPurchase ,
153+ estimatedDaysUntilPurchase ,
154+ ] ;
155+
156+ return (
157+ knownIntervals . reduce ( ( sum , interval ) => sum + interval , 0 ) /
158+ knownIntervals . length
159+ ) ;
160+ }
0 commit comments