-
Notifications
You must be signed in to change notification settings - Fork 45
/
02_ord.ts
95 lines (75 loc) · 2.33 KB
/
02_ord.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
**Quiz**. Dato un tipo `A` è possibile definire una istanza di semigruppo
per `Ord<A>`. Cosa potrebbe rappresentare?
*/
import { pipe } from 'fp-ts/function'
import * as O from 'fp-ts/Ord'
import { sort } from 'fp-ts/ReadonlyArray'
import { concatAll, Semigroup } from 'fp-ts/Semigroup'
import * as S from 'fp-ts/string'
import * as N from 'fp-ts/number'
import * as B from 'fp-ts/boolean'
/*
prima di tutto definiamo una istanza di semigrouppo per `Ord<A>`
*/
const getSemigroup = <A = never>(): Semigroup<O.Ord<A>> => ({
concat: (first, second) =>
O.fromCompare((a1, a2) => {
const ordering = first.compare(a1, a2)
return ordering !== 0 ? ordering : second.compare(a1, a2)
})
})
/*
adesso vediamola applicata ad un esempio pratico
*/
interface User {
readonly id: number
readonly name: string
readonly age: number
readonly rememberMe: boolean
}
const byName = pipe(
S.Ord,
O.contramap((_: User) => _.name)
)
const byAge = pipe(
N.Ord,
O.contramap((_: User) => _.age)
)
const byRememberMe = pipe(
B.Ord,
O.contramap((_: User) => _.rememberMe)
)
const SemigroupOrdUser = getSemigroup<User>()
// rappresenta una tabella da ordinare
const users: ReadonlyArray<User> = [
{ id: 1, name: 'Guido', age: 47, rememberMe: false },
{ id: 2, name: 'Guido', age: 46, rememberMe: true },
{ id: 3, name: 'Giulio', age: 44, rememberMe: false },
{ id: 4, name: 'Giulio', age: 44, rememberMe: true }
]
// un ordinamento classico:
// prima per nome, poi per età, poi per `rememberMe`
const byNameAgeRememberMe = concatAll(SemigroupOrdUser)(byName)([
byAge,
byRememberMe
])
pipe(users, sort(byNameAgeRememberMe), console.log)
/*
[ { id: 3, name: 'Giulio', age: 44, rememberMe: false },
{ id: 4, name: 'Giulio', age: 44, rememberMe: true },
{ id: 2, name: 'Guido', age: 46, rememberMe: true },
{ id: 1, name: 'Guido', age: 47, rememberMe: false } ]
*/
// adesso invece voglio tutti gli utenti con
// `rememberMe = true` per primi
const byRememberMeNameAge = concatAll(SemigroupOrdUser)(
O.reverse(byRememberMe)
)([byName, byAge])
pipe(users, sort(byRememberMeNameAge), console.log)
/*
[ { id: 4, name: 'Giulio', age: 44, rememberMe: true },
{ id: 2, name: 'Guido', age: 46, rememberMe: true },
{ id: 3, name: 'Giulio', age: 44, rememberMe: false },
{ id: 1, name: 'Guido', age: 47, rememberMe: false } ]
*/