SHARE
TWEET

Untitled

a guest Jul 19th, 2019 49 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const curry = require("ramda").curry;
  2. const reduce = require("ramda").reduce;
  3. const compose = require("ramda").compose;
  4. const concat = require("ramda").concat;
  5.  
  6. const Maybe = require("@mostly-adequate/support").Maybe;
  7.  
  8. // the 'maybe' function returns an error message when the given Maybe isNothing,
  9. //   or the result of applying a given fn to the value in the Maybe.
  10. // maybe :: b -> (a -> b) -> Maybe a -> b
  11. const maybe = curry((alt, fn, aMaybe) => aMaybe.isNothing ? alt : fn(aMaybe.$value));
  12.  
  13. const prependString = curry((str, val) => `${str} ${val}`);
  14.  
  15. // wraps a value in a function, used in places where a function is needed,
  16. //   but you want the value given to the function.
  17. const returnTheValue = val => val;
  18.  
  19. // Allows dot notation instead of array segments as in Ramda's 'path' function
  20. const elvis = curry((path, object) =>
  21.   path ? reduce((value, key) =>
  22.     value && value[key], object, path.split(".")) : object
  23. );
  24.  
  25. // Wraps elvis in a Maybe Monad so they can't harm him
  26. const safeElvis = curry((path, object) => Maybe.of(elvis(path, object)));
  27.  
  28. const getHeightWrongly = safeElvis("metadata.attributes.BLAH.value");
  29. const getHeight = safeElvis("metadata.attributes.height.value");
  30.  
  31. // composeSuccessMessage :: Maybe m -> string b
  32. const composeSuccessMessage = compose(prependString("Found a person's height:"), returnTheValue);
  33.  
  34. const person = {
  35.   name: 'I am second',
  36.   metadata: {
  37.     attributes: {
  38.       height: {
  39.         value: 23
  40.       }
  41.     }
  42.   }
  43. };
  44.  
  45. const result1 = maybe("Wrong path!", returnTheValue, getHeightWrongly(person)); // Nothing as "Wrong path!"
  46. const result2 = maybe("Wrong path!", composeSuccessMessage, getHeight(person)); // Just(23) as "Found a person's height: 23"
  47.  
  48. console.log(result1);
  49. console.log(result2);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top