Last active
December 28, 2021 04:26
-
-
Save alexeyraspopov/91c1d31f9a63c18c9141 to your computer and use it in GitHub Desktop.
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
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); | |
} |
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
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