Skip to content

Commit

Permalink
✨ Refactor useFetchTasks()'s select function (#1216)
Browse files Browse the repository at this point in the history
The motivation for this refactoring came while working on #1191 and
trying to understand what tasks were given to the analysis table. The
select 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.

Output of the refactored function is functionally identical to the
original implementation.

Signed-off-by: Scott J Dickerson <sdickers@redhat.com>
  • Loading branch information
sjd78 authored Jul 28, 2023
1 parent e59e1d0 commit dde1712
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 dde1712

Please sign in to comment.