Sniberb
Sniberb2y ago

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 };
};
2 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
reactibot
reactibot2y ago
This thread hasn’t had any activity in 36 hours, so it’s now locked. Threads are closed automatically after 36 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/565213527673929729/1121725459328151562