-
Notifications
You must be signed in to change notification settings - Fork 16
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Genericize filterObjects and add to tui common
- Loading branch information
Showing
3 changed files
with
134 additions
and
109 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
// Type that matches property values of type T if and only if the value of | ||
// that property is a string or undefined | ||
export type PropsOfObjectWithValuesOfType<T, V> = { | ||
[K in keyof T]: T[K] extends V ? K : never; | ||
}[keyof T]; | ||
|
||
export type OrderBy = 'ASC' | 'DESC'; | ||
|
||
export const filterObjects = <T extends {}, U = string | undefined>( | ||
objects: Array<T>, | ||
groupBy: PropsOfObjectWithValuesOfType<T, U>, | ||
orderGroupBy: OrderBy = 'ASC' | ||
): Array<[string, Array<T>]> => { | ||
let objectsByProp: { [key: string]: Array<T> } = {}; | ||
for (let obj of objects) { | ||
// Cannot filter on values that are undefined. | ||
if (obj[groupBy] === undefined) { | ||
continue; | ||
} | ||
|
||
// Create groupBy key if it doesn't exist and add the object to an empty | ||
// array | ||
const key = obj[groupBy] as unknown as string; | ||
if (objectsByProp[key] === undefined) { | ||
objectsByProp[key] = [obj]; | ||
continue; | ||
} | ||
|
||
objectsByProp[key] = [...objectsByProp[key], obj]; | ||
} | ||
|
||
const filteredObjects = Object.entries(objectsByProp).sort((a, b) => | ||
a[0].localeCompare(b[0]) | ||
); | ||
return orderGroupBy === 'ASC' ? filteredObjects : filteredObjects.reverse(); | ||
}; |
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