Skip to content

Instantly share code, notes, and snippets.

@scornork
Last active January 26, 2025 12:32
Show Gist options
  • Save scornork/846bc1dfb69b9d14569a77f8bc3f13af to your computer and use it in GitHub Desktop.
Save scornork/846bc1dfb69b9d14569a77f8bc3f13af to your computer and use it in GitHub Desktop.
Implementation of the Either monad in a closure.
const Either = Object.freeze((() => {
const Right = input => ({
get isRight () {
return _ => true;
},
get isLeft () {
return _ => false;
},
get chain () {
return handle => handle(input);
},
get fold () {
return (_, handle) => handle(input);
},
get map () {
return handle => Right(handle(input));
}
});
const Left = error => ({
get isRight () {
return _ => false;
},
get isLeft () {
return _ => true;
},
get chain () {
return _ => Left(error);
},
get fold () {
return (handle, _) => handle(error);
},
get map () {
return _ => Left(error);
}
});
return Object.freeze({
get right () {
return input => Right(input);
},
get left () {
return error => Left(error);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment