Last active
September 12, 2017 21:52
-
-
Save harmenjanssen/e70f3df691194e892953ff9bec110efe to your computer and use it in GitHub Desktop.
`prop` and `propIn` utility functions using the Maybe monad.
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 :: ?a -> Maybe a | |
export const maybe = x => { | |
return x != null && x !== undefined ? Just(x) : Nothing; | |
}; | |
// identity :: a -> a | |
export const identity = x => x; | |
// prop :: String -> Object -> Maybe x | |
export const prop = x => o => maybe(o[x]); | |
// propIn :: Array -> Object -> Maybe b | |
export const propIn = xs => | |
o => xs.reduce((acc, cur) => acc.chain(prop(cur)), Just(o)); |
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 | |
* | |
* Shout out to Tom Harding whose article this was blatantly stolen from: | |
* http://www.tomharding.me/2016/12/31/yippee-ki-yay-other-functors/ | |
*/ | |
/** | |
* Maybe | |
*/ | |
export const Just = x => ({ | |
// Transform the inner value | |
// map :: Maybe a ~> (a -> b) -> Maybe b | |
map: f => Just(f(x)), | |
// chain :: Maybe a ~> (a -> b) -> Maybe b | |
chain(f) { | |
return this.map(f).fold(undefined, identity); | |
}, | |
// Get the inner value | |
// fold :: Maybe a ~> (b, a -> b) -> b | |
fold: (_, f) => f(x), | |
// toString :: Just a ~> String | |
toString: () => `Just(${x})` | |
}); | |
export const Nothing = { | |
// Do nothing | |
// map :: Maybe a ~> (a -> b) -> Maybe b | |
map: f => Nothing, | |
// chain :: Maybe a ~> (a -> b) -> Maybe b | |
chain: f => Nothing, | |
// Return the default value | |
// fold :: Maybe a ~> (b, a -> b) -> b | |
fold: (d, _) => d, | |
// toString :: Nothing a ~> String | |
toString: () => `Nothing` | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment