Last active
February 2, 2024 12:40
-
-
Save SanichKotikov/c8c3dac1f0de4b722b13c4af49b29c61 to your computer and use it in GitHub Desktop.
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
// utils/types.ts | |
type KeysOfType<O, T> = { [K in keyof O]: O[K] extends T ? K : never }[keyof O]; | |
// utils/array.ts | |
function inAbcOrderBy<T extends object, K extends KeysOfType<T, string>>(prop: K) { | |
return (a: T, b: T): number => { | |
return (a[prop] as string).localeCompare(b[prop] as string); | |
}; | |
} | |
function inCustomOrderBy< | |
T extends object, | |
K extends keyof T, | |
V extends T[K] | |
>(prop: K, order: V[]) { | |
return (a: T, b: T): number => { | |
return order.indexOf(a[prop] as V) - order.indexOf(b[prop] as V); | |
}; | |
} | |
function inPriority<T extends object>(...sorters: Array<(a: T, b: T) => number>) { | |
return (a: T, b: T): number => { | |
for (let i = 0; i < sorters.length; i++) { | |
const result = sorters[i](a, b); | |
if (result !== 0) return result; | |
} | |
return 0; | |
}; | |
} | |
// features/types.ts | |
enum FeatureType { | |
Default = 'default', | |
Local = 'local', | |
Unknown = 'unknown', | |
} | |
interface Feature { | |
title: string; | |
type: FeatureType; | |
} | |
// featutes/utils.ts | |
const TYPE_ORDER = [ | |
FeatureType.Default, | |
FeatureType.Local, | |
FeatureType.Unknown, | |
]; | |
function sortFeaturesByTypeAndTitle(features: Feature[]): Feature[] { | |
return [...features].sort( | |
inPriority( | |
inCustomOrderBy('type', TYPE_ORDER), | |
inAbcOrderBy('title') | |
) | |
); | |
} | |
// main code | |
const items: Feature[] = [ | |
{ title: 'images', type: FeatureType.Unknown }, | |
{ title: 'users', type: FeatureType.Local }, | |
{ title: 'posts', type: FeatureType.Default }, | |
{ title: 'articles', type: FeatureType.Default }, | |
]; | |
console.log(sortFeaturesByTypeAndTitle(items)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment