Skip to content

Commit

Permalink
feat(#13): implement sort list by purchase history
Browse files Browse the repository at this point in the history
export function comparePurchaseUrgency

dates.js: update param name and logic to handle future and past dates

List.jsx: import comparePurchaseUrgency
  • Loading branch information
dterceroparker committed Sep 16, 2024
1 parent f21161b commit bdec39e
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
15 changes: 15 additions & 0 deletions src/api/firebase.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,21 @@ export async function shareList(listPath, currentUserId, recipientEmail) {
);
}

export function comparePurchaseUrgency(list) {
// Create a copy of the list to avoid mutating original array
const sortedList = [...list].sort((a, b) => {
const daysA = getDaysBetweenDates(a.dateNextPurchased);
const daysB = getDaysBetweenDates(b.dateNextPurchased);
// Inactive items (60 days or more)
// Sort by dats until next purchase
if (daysA < daysB) return -1;
if (daysB < daysA) return 1;
// If days are the same, sort alphabetically
return a.name.localeCompare(b.name);
});
return sortedList;
}

/**
* Add a new item to the user's list in Firestore.
* @param {string} listPath The path of the list we're adding to.
Expand Down
9 changes: 6 additions & 3 deletions src/utils/dates.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ const ONE_DAY_IN_MILLISECONDS = 86400000;
export function getFutureDate(offset) {
return new Date(Date.now() + offset * ONE_DAY_IN_MILLISECONDS);
}
export function getDaysBetweenDates(previousPurchaseDate) {
const pastDate = previousPurchaseDate.toDate();
export function getDaysBetweenDates(dateToCompare) {
const comparisonDate = dateToCompare.toDate();
console.log(comparisonDate);
const presentDate = new Date();
const diffInMilliseconds = presentDate.getTime() - pastDate.getTime();
const diffInMilliseconds = Math.abs(
presentDate.getTime() - comparisonDate.getTime(),
);
return Math.round(diffInMilliseconds / ONE_DAY_IN_MILLISECONDS);
}
1 change: 1 addition & 0 deletions src/views/List.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useState } from 'react';
import { ListItem } from '../components';
import { NavLink } from 'react-router-dom';
import { comparePurchaseUrgency } from '../api/firebase';

export function List({ data, listPath }) {
const [searchInput, setSearchInput] = useState('');
Expand Down

0 comments on commit bdec39e

Please sign in to comment.