Last active
February 8, 2019 14:55
-
-
Save AvocadoVenom/ca64de0b3175d32e5f67dc63b4bcdcf3 to your computer and use it in GitHub Desktop.
Transform a list of items into a smaller one (containing X elements). Keep the X-1 first items and concatenate the remaining into one single item.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Keep the @param nb first values of the list @param values. | |
* Apply the @param reduceFn function to "concatenate" the remaining values. | |
* @param values List of values/objects. | |
* @param nb Final number of values in the list. | |
* @param orderingFn Function to use to order the list. | |
* @param reduceFn Reduction function to group exceeding items. | |
*/ | |
export function summarizeList<T>(values: T[], nb: number = 10, orderingFn: (a: T, b: T) => number, reduceFn: (list: T[]) => T) { | |
// From nb+ values, we trigger the grouping | |
if (values.length > nb) { | |
// Sort the list. | |
const orderedValues = values.sort(orderingFn); | |
// nb-1 => the last item is the grouping item | |
const smallValues = orderedValues.slice(nb - 1); | |
// Build grouping item. | |
const grouped = reduceFn(smallValues); | |
// Remove the small values from the initial list. | |
smallValues.forEach(x => values.splice(values.indexOf(x), 1)); | |
// Add the grouping item to the list. | |
values.push(grouped); | |
} | |
return values; | |
} | |
// Usage: Get 3 highest values and group the remaining (useful for pie charts to group small values). | |
const arr = [ | |
{ value: 1 }, | |
{ value: 2 }, | |
{ value: 3 }, | |
{ value: 4 }, | |
{ value: 5 }, | |
{ value: 6 }, | |
]; | |
const summarizedList = summarizeList( | |
arr, | |
4, | |
(a, b) => Math.abs(b.value) - Math.abs(a.value), | |
(remaining) => ({ value: remaining.reduce((s, i) => s+i.value, 0) }) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment