Skip to content

Instantly share code, notes, and snippets.

@domjancik
Last active March 15, 2021 15:15
Show Gist options
  • Save domjancik/64e50c4915b59d151b71aa4e91d7dbf6 to your computer and use it in GitHub Desktop.
Save domjancik/64e50c4915b59d151b71aa4e91d7dbf6 to your computer and use it in GitHub Desktop.
fp-ts ordering by object keys with localeCompare
import * as A from 'fp-ts/Array'
import * as R from 'fp-ts/Record'
import { pipe } from 'fp-ts/function'
import { contramap, Ord, clamp, ordNumber } from 'fp-ts/Ord'
import { Ordering } from 'fp-ts/Ordering'
import { fst } from 'fp-ts/Tuple'
const o: { [key: string]: string } = {
"a-tag": "stuff",
"c-tag": "even more stuff",
"b-tag": "more stuff",
}
const ordLocaleString: Ord<string> = {
equals: (first, second) => first.localeCompare(second) === 0,
// Ordering needs to be -1, 0 or 1. localeCompare may return values outside https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare#description
compare: (first, second) => pipe(first.localeCompare(second), clamp(ordNumber)(-1, 1)) as Ordering
}
const byKey: Ord<[string, string]> = contramap(fst)(ordLocaleString)
const res = pipe(
o,
R.toArray,
A.sort(byKey)
)
res // [ [ 'a-tag', 'stuff' ], [ 'b-tag', 'more stuff' ], [ 'c-tag', 'even more stuff' ] ] 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment