Skip to content

Instantly share code, notes, and snippets.

@alexeyraspopov
Last active December 28, 2021 04:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexeyraspopov/91c1d31f9a63c18c9141 to your computer and use it in GitHub Desktop.
Save alexeyraspopov/91c1d31f9a63c18c9141 to your computer and use it in GitHub Desktop.
Maybe(13)
.bind(a => a * a)
.bind(log);
isWorthy("Loki")
.bind(null, () => Just("Vision"))
.bind(name => log(name, "is worthy"));
function isWorthy(name) {
return name === "Thor" ? Just(name) : Nothing();
}
function log() {
console.log.apply(console, arguments);
}
function Maybe(value) {
return isNullable(value) ? Nothing() : Just(value);
}
function Just(value) {
return isMonad(value) ? value : Monad(value, bindJust);
}
function Nothing() {
return Monad(void 0, bindNothing);
}
function Monad(value, operator) {
return {
isMonad: true,
bind: function(right, left) {
return operator(value, right, left);
}
};
}
function bindJust(value, morphism) {
return isFunction(morphism) ? Just(morphism(value)) : Just(value);
}
function bindNothing(value, right, morphism) {
return isFunction(morphism) ? Just(morphism()) : Nothing();
}
function isMonad(value) {
return value && value.isMonad;
}
function isFunction(value) {
return value instanceof Function;
}
function isNullable(value) {
return value === void 0 || value === null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment