Skip to content

Instantly share code, notes, and snippets.

@gcanti
Last active March 23, 2018 16:54
Show Gist options
  • Save gcanti/e020c7bf9d996f2ee4730d5dcb8b8461 to your computer and use it in GitHub Desktop.
Save gcanti/e020c7bf9d996f2ee4730d5dcb8b8461 to your computer and use it in GitHub Desktop.
Functional TypeScript: Either vs Validation
import { HKT, URIS2, Type2 } from 'fp-ts/lib/HKT'
import { Applicative, Applicative2, Applicative2C } from 'fp-ts/lib/Applicative'
type Errors = Array<string>
function checkAge<M extends URIS2>(
applicative: Applicative2<M>,
fail: (errors: Errors) => Type2<M, Errors, Person>
): (p: Person) => Type2<M, Errors, Person>
function checkAge<M extends URIS2>(
applicative: Applicative2C<M, Errors>,
fail: (errors: Errors) => Type2<M, Errors, Person>
): (p: Person) => Type2<M, Errors, Person>
function checkAge<M>(
applicative: Applicative<M>,
fail: (errors: Errors) => HKT<M, Person>
): (p: Person) => HKT<M, Person> {
return p => {
if (p.age < 18) {
return fail(['Too Young!'])
} else if (p.age > 40) {
return fail(['Too Old!'])
}
return applicative.of(p)
}
}
function checkClothes<M extends URIS2>(
applicative: Applicative2<M>,
fail: (errors: Errors) => Type2<M, Errors, Person>
): (p: Person) => Type2<M, Errors, Person>
function checkClothes<M extends URIS2>(
applicative: Applicative2C<M, Errors>,
fail: (errors: Errors) => Type2<M, Errors, Person>
): (p: Person) => Type2<M, Errors, Person>
function checkClothes<M>(
applicative: Applicative<M>,
fail: (errors: Errors) => HKT<M, Person>
): (p: Person) => HKT<M, Person> {
return p => {
if (p.gender === 'Male' && p.clothes.indexOf('Tie') === -1) {
return fail(['Smarten Up!'])
} else if (p.gender === 'Female' && p.clothes.indexOf('Trainers') !== -1) {
return fail(['Wear high heels'])
}
return applicative.of(p)
}
}
function checkSobriety<M extends URIS2>(
applicative: Applicative2<M>,
fail: (errors: Errors) => Type2<M, Errors, Person>
): (p: Person) => Type2<M, Errors, Person>
function checkSobriety<M extends URIS2>(
applicative: Applicative2C<M, Errors>,
fail: (errors: Errors) => Type2<M, Errors, Person>
): (p: Person) => Type2<M, Errors, Person>
function checkSobriety<M>(
applicative: Applicative<M>,
fail: (errors: Errors) => HKT<M, Person>
): (p: Person) => HKT<M, Person> {
return p => {
if (['Drunk', 'Paralytic', 'Unconscious'].indexOf(p.sobriety) !== -1) {
return fail(['Sober Up!'])
}
return applicative.of(p)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment