Skip to content

Commit

Permalink
Refactor useFetchTasks()'s select function
Browse files Browse the repository at this point in the history
The function used by `useFetchTasks()` to filter by addon and to
keep only the newest tasks per application id was confusing to
read as written.  This refactor simplifies the steps involved
to use a typical stream processing approach.

The output is functionally identical to the original implementation.

Signed-off-by: Scott J Dickerson <[email protected]>
  • Loading branch information
sjd78 committed Jul 27, 2023
1 parent 6ab92d3 commit 69b79f4
Showing 1 changed file with 21 additions and 21 deletions.
42 changes: 21 additions & 21 deletions client/src/app/queries/tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,28 @@ export const useFetchTasks = (filters: FetchTasksFilters = {}) => {
{
refetchInterval: 5000,
select: (allTasks) => {
const filteredTasks = filters
? allTasks.filter((task) => {
return !filters.addon || task.addon === filters.addon;
})
: allTasks;
let uniqLatestTasks: Task[] = [];
filteredTasks.forEach((task) => {
const aTask = uniqLatestTasks.find(
(item) => task.application?.id === item.application?.id
const uniqSorted = allTasks
.filter((task) =>
filters?.addon ? filters.addon === task.addon : true
)
// sort by application.id (ascending) then createTime (newest to oldest)
.sort((a, b) => {
if (a.application.id !== b.application.id) {
return a.application.id - b.application.id;
} else {
const aTime = a?.createTime ?? "";
const bTime = b?.createTime ?? "";
return aTime < bTime ? 1 : aTime > bTime ? -1 : 0;
}
})
// remove old tasks for each application
.filter(
(task, index, tasks) =>
index === 0 ||
task.application.id !== tasks[index - 1].application.id
);
if (!aTask) {
uniqLatestTasks.push(task);
} else if (
aTask?.createTime &&
task?.createTime &&
task.createTime > aTask.createTime
) {
const others = uniqLatestTasks.filter((t) => t.id !== aTask.id);
uniqLatestTasks = [...others, task];
}
});
return uniqLatestTasks;

return uniqSorted;
},
onError: (err) => console.log(err),
}
Expand Down

0 comments on commit 69b79f4

Please sign in to comment.