'Compare array with enum values and priority the results / simplify solution
I have a solution that takes an input (array with multiple objects) and then compares said input with three different enums that have three different prioritizations and return the length/count of the matched values. I then need to check which enum the count/number belongs too. I have a working solution, but the code seems unnecessary repeated and can be simplified. How to do that, is my question. Playground.
Idea is to compare with the highest prioritized enum and if its any matches, return the length and then chec
export enum prio1 {
value1
}
export enum prio2 {
value2
}
export enum prio3 {
value3
}
export var subHeader: RemoteJobsStatus;
export var count = 0;
export const dataArray = [{
value: 'value3'
}
]
I then have a function that takes in the input data, sends it to another function that compares the values and then sends the length/count. getStatusCount();
function getStatusCount() {
let results = null;
results = [getNumberOfStatus(prio1, dataArray),
getNumberOfStatus(prio2, dataArray),
getNumberOfStatus(prio3, dataArray)
];
switch (true) {
case (results[0] > 0):
subHeader = RemoteJobsStatus.Ongoing;
count = results[0];
console.log(subHeader, count, results);
break;
case (results[1] > 0):
subHeader = RemoteJobsStatus.Pending;
count = results[1];
console.log(subHeader, count, results);
break;
case (results[2] > 0):
subHeader = RemoteJobsStatus.Failed;
count = results[2];
console.log(subHeader, count, results);
break;
default: return;
}
}
The filtering function will take two parameters of the input data, and the enums what will be compared to the data:
function getNumberOfStatus(statusVariants: typeof prio1 | typeof prio2 | typeof prio3, jobs: any) {
const nrOfStatus = dataArray.map((j:any) =>
Object.values(statusVariants)?.includes(j.value as string)).filter(Boolean).length;
return nrOfStatus;
}
How to simplify the above working code? It seems there is a lot of unnecessary repeating of code, and don't think I need a switch statement at all.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
