1
0
mirror of https://github.com/dzeiocom/libs.git synced 2025-08-04 19:01:58 +00:00

Updated objectSort to support an Array containing a specific order

Signed-off-by: Avior <florian.bouillon@delta-wings.net>
This commit is contained in:
2021-04-11 00:34:14 +02:00
parent 485e3b7b36
commit 76e2263812
3 changed files with 29 additions and 5 deletions

View File

@@ -62,12 +62,18 @@ export function objectSize(obj: Record<string, any>): number {
* @param obj the object to sort
* @param fn (Optionnal) the function to run to sort
*/
export function objectSort<T = Record<string, any>>(
obj: Record<string, any>,
fn?: (a: string, b: string) => number
export function objectSort<T extends Record<string, any> = Record<string, any>>(
obj: T,
fn?: Array<keyof T> | ((a: keyof T, b: keyof T) => number)
): T {
const ordered: any = {}
for (const key of objectKeys(obj).sort(fn)) {
let sortedKeys: Array<keyof T> = []
if (Array.isArray(fn)) {
sortedKeys = fn.concat(objectKeys(obj).filter((k) => !fn.includes(k)))
} else {
sortedKeys = objectKeys(obj).sort(fn)
}
for (const key of sortedKeys) {
ordered[key] = obj[key]
}
return ordered