Last active
January 6, 2019 12:41
-
-
Save VincentCordobes/3556fc53631bf4b608cb0ded90eb114c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Add = (a: number) => (b: number) => (c: number) => number; | |
const add: Add = a => b => c => a + b + c; | |
const r = succeed(4).map(add).ap(fail(['err1'])).ap(fail(['err2'])); | |
// const r = succeed(add).ap(succeed(4)).ap(succeed(1)).ap(succeed(2)); | |
// console.log(r); | |
type Person = { | |
firstname: string, | |
lastname: string, | |
age: number, | |
} | |
type CreatePerson = (firstname: string) => (lastname: string) => (age: number) => Person; | |
const createPerson: CreatePerson = firstname => lastname => age => ({ | |
firstname, | |
lastname, | |
age, | |
}); | |
function createAge(age: number): Result<number, string[]> { | |
if (age < 0) { | |
return fail(["Age must be positive"]); | |
} else if (age > 100) { | |
return fail(["Age must be positive"]); | |
} else { | |
return succeed(age); | |
} | |
} | |
function createFirstname(firstname: string): Result<string, string[]> { | |
if (firstname.length > 10) { | |
return fail(["invalid firstname"]) | |
} else { | |
return succeed(firstname); | |
} | |
} | |
function createLastname(lastname: string): Result<string, string[]> { | |
if (lastname.length > 10) { | |
return fail(["invalid lastname"]) | |
} else { | |
return succeed(lastname); | |
} | |
} | |
function validatePerson(firstname: string, lastname: string, age: number): Result<Person, string[]>{ | |
const firstnameRes = createFirstname(firstname); | |
const lastnameRes = createLastname(lastname); | |
const ageRes = createAge(age); | |
return firstnameRes.map(createPerson).ap(firstnameRes).ap(lastnameRes).ap(ageRes); | |
} | |
console.log(validatePerson('Vincent', 'Cordobes', -14)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment