Skip to content

Instantly share code, notes, and snippets.

@harmenjanssen
Last active September 12, 2017 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harmenjanssen/e70f3df691194e892953ff9bec110efe to your computer and use it in GitHub Desktop.
Save harmenjanssen/e70f3df691194e892953ff9bec110efe to your computer and use it in GitHub Desktop.
`prop` and `propIn` utility functions using the Maybe monad.
// 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));
/**
* 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