Created
January 22, 2020 15:38
-
-
Save Willmo36/912bffa0d20838eceb6359e996895d69 to your computer and use it in GitHub Desktop.
FP-TS Priority type
This file contains hidden or 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
import * as Ord from 'fp-ts/lib/Ord'; | |
import * as Eq from 'fp-ts/lib/Eq'; | |
import {pipe} from 'fp-ts/lib/pipeable'; | |
import * as Array from 'fp-ts/lib/Array'; | |
import * as NonEmptyArray from 'fp-ts/lib/NonEmptyArray'; | |
export type Priority<A> = { | |
priority: number; | |
value: A; | |
}; | |
export const withPriority = (priority: number) => <A>( | |
value: A, | |
): Priority<A> => ({priority, value}); | |
export const getEqPriority = <A>(eqValue: Eq.Eq<A>): Eq.Eq<Priority<A>> => | |
Eq.contramap<A, Priority<A>>(wp => wp.value)(eqValue); | |
export const getOrdPriority = <A>( | |
ordValue: Ord.Ord<A>, | |
): Ord.Ord<Priority<A>> => ({ | |
...getEqPriority(ordValue), | |
compare(a, b) { | |
//Order by priority | |
const priorityOrdering = Ord.ordNumber.compare(a.priority, b.priority); | |
//if priorities are equal, use the value ordering | |
if (priorityOrdering === 0) { | |
return ordValue.compare(a.value, b.value); | |
} else { | |
return priorityOrdering; | |
} | |
}, | |
}); | |
export const sortGroupByPriority = <A>(ord: Ord.Ord<Priority<A>>) => ( | |
as: Priority<A>[], | |
) => | |
pipe( | |
as, | |
Array.sort(ord), | |
NonEmptyArray.group(ord), | |
Array.map(NonEmptyArray.sort(ord)), | |
); | |
export const uniqByPriority = <A>(ord: Ord.Ord<Priority<A>>) => ( | |
as: Priority<A>[], | |
) => | |
pipe( | |
as, | |
sortGroupByPriority(ord), | |
Array.map(NonEmptyArray.head), | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment