snowberb – 08-56 Jun 23

I've made this function and I really think it can be improved for some readability (readability > performace), any further help is appreciated. What it does is: Sort by biggest number first, then depending on the contributionType, it either takes the first 10 elements into one array and the rest are saved to others array, or takes first 5 and last 5 elements, and the rest to others array excluding the already sliced items
const getChartData = (data: Contribution[], contributionType: ContributionTypeEnum) => {
const sortedData = [...data].sort((a, b) => b.volatility - a.volatility);
let first10: Contribution[] = [];
let others: Contribution[] = [];

if (contributionType !== 'INSTRUMENTS') {
first10 = sortedData.slice(0, 10);

if (sortedData.length > 10) {
others = sortedData.slice(10);
}
} else {
const first5 = sortedData.slice(0, 5);
let last5: Contribution[] = [];

if (sortedData.length > 5) {
if (sortedData.length <= 10) {
last5 = sortedData.slice(5, sortedData.length);
} else {
last5 = sortedData.slice(-5);

others = sortedData.slice(5, sortedData.length - 1 - 5);
}
}

first10 = [...first5, ...last5];
}

return { data: first10, others };
};
const getChartData = (data: Contribution[], contributionType: ContributionTypeEnum) => {
const sortedData = [...data].sort((a, b) => b.volatility - a.volatility);
let first10: Contribution[] = [];
let others: Contribution[] = [];

if (contributionType !== 'INSTRUMENTS') {
first10 = sortedData.slice(0, 10);

if (sortedData.length > 10) {
others = sortedData.slice(10);
}
} else {
const first5 = sortedData.slice(0, 5);
let last5: Contribution[] = [];

if (sortedData.length > 5) {
if (sortedData.length <= 10) {
last5 = sortedData.slice(5, sortedData.length);
} else {
last5 = sortedData.slice(-5);

others = sortedData.slice(5, sortedData.length - 1 - 5);
}
}

first10 = [...first5, ...last5];
}

return { data: first10, others };
};
UU
Unknown User297d ago