Skip to content

Commit

Permalink
add getMonoid to Ord
Browse files Browse the repository at this point in the history
  • Loading branch information
vicrac authored and gcanti committed Dec 16, 2019
1 parent b480c7d commit b1102b7
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Ord.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { Semigroup } from './Semigroup'
import { Eq } from './Eq'
import { Contravariant1 } from './Contravariant'
import { pipeable } from './pipeable'
import { Monoid } from './Monoid'

declare module './HKT' {
interface URItoKind<A> {
Expand Down Expand Up @@ -226,6 +227,18 @@ export function getSemigroup<A = never>(): Semigroup<Ord<A>> {
}
}

const empty = fromCompare(() => 0)

/**
* @since 2.4.0
*/
export function getMonoid<A = never>(): Monoid<Ord<A>> {
return {
empty,
concat: getSemigroup<A>().concat
}
}

/**
* Given a tuple of `Ord`s returns an `Ord` for the tuple
*
Expand Down
29 changes: 29 additions & 0 deletions test/Ord.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
clamp,
getDualOrd,
getSemigroup,
getMonoid,
ordDate,
ordNumber,
ordString,
Expand All @@ -15,6 +16,7 @@ import {
getTupleOrd,
ordBoolean
} from '../src/Ord'
import { fold } from '../src/Monoid'

describe('Ord', () => {
it('getTupleOrd', () => {
Expand Down Expand Up @@ -51,6 +53,33 @@ describe('Ord', () => {
])
})

it('getMonoid', () => {
interface Person {
name: string
age: number
}
const people: Person[] = [
{ name: 'John', age: 42 },
{ name: 'Dorothy', age: 37 },
{ name: 'John', age: 37 }
]

const sortByName = ord.contramap(ordString, (p: Person) => p.name)
const sortByAge = ord.contramap(ordNumber, (p: Person) => p.age)

const monoid = getMonoid<Person>()
const sortByNameByAge = fold(monoid)([sortByName, sortByAge])
const dontSort = fold(monoid)([])

assert.deepStrictEqual(sort(sortByNameByAge)(people), [
{ name: 'Dorothy', age: 37 },
{ name: 'John', age: 37 },
{ name: 'John', age: 42 }
])

assert.deepStrictEqual(sort(dontSort)(people), people)
})

it('ordNumber', () => {
assert.strictEqual(ordNumber.compare(1, 2), -1)
assert.strictEqual(ordNumber.compare(2, 1), 1)
Expand Down

0 comments on commit b1102b7

Please sign in to comment.