Last active
January 13, 2018 00:32
-
-
Save thiagoh/eb81d8b99da88754cba7fd9ebd23663f to your computer and use it in GitHub Desktop.
monad in practice
This file contains hidden or 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
const PersonMonad = person => { | |
const ValidMon = failList => { | |
return { | |
map: ({ f, error }) => { | |
if (!f(person)) { | |
failList.push(error); | |
} | |
return ValidMon(failList); | |
}, | |
flatMap: ({ f, error }) => { | |
if (!f(person)) { | |
failList.push(error); | |
} | |
return failList; | |
}, | |
value: () => failList | |
}; | |
}; | |
return Object.create({ | |
map: f => PersonMonad(f(person)), | |
flatMap: f => f(person), | |
validation: () => ValidMon([]) | |
}); | |
}; | |
const Validation = { | |
validAge: { f: p => p.age >= 18, error: "Error: age is not valid" }, | |
validName: { f: p => p.name.length > 3, error: "Error: name is not valid" } | |
}; | |
console.log( | |
PersonMonad({ age: 12, name: "thiago andrade" }) | |
.validation() | |
.map(Validation.validAge) | |
.map(Validation.validName) | |
.value() | |
); | |
// OR | |
console.log( | |
PersonMonad({ age: 12, name: "thiago andrade" }) | |
.validation() | |
.map(Validation.validAge) | |
.flatMap(Validation.validName) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment