Sort by a specific field with custom ordering

Useful to make reusable sorting components.

import { DateTime } from "luxon"  
  
// https://gcanti.github.io/fp-ts/modules/Ord.ts.html  
export const DateTimeOrd: Ord.Ord<DateTime> = {  
 equals: (x: DateTime, y: DateTime) => x.equals(y), compare: (first: DateTime, second: DateTime) => first < second ? 1 : first > second ? -1 : 0,}  
  
interface Foo {  
 bar: number modifiedAt: DateTime}  
  
const sortByModifiedAt = sort(  
 pipe( DateTimeOrd, Ord.contramap((foo: Foo) => foo.modifiedAt) // 🎉choose a field here ))  
  
const now = DateTime.local()  
  
const sorted = sortByModifiedAt([  
 { bar: 1, modifiedAt: now }, { bar: 2, modifiedAt: now.minus({ days: 1 }) },])  

More info:

  • https://gcanti.github.io/fp-ts/modules/Array.ts.html#sort

  • https://gcanti.github.io/fp-ts/modules/Ord.ts.html


    Would you like to connect? Subscribe via email or RSS , or follow me on Twitter!