Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const curry = require("ramda").curry;
- const reduce = require("ramda").reduce;
- const compose = require("ramda").compose;
- const concat = require("ramda").concat;
- const Maybe = require("@mostly-adequate/support").Maybe;
- // the 'maybe' function returns an error message when the given Maybe isNothing,
- // or the result of applying a given fn to the value in the Maybe.
- // maybe :: b -> (a -> b) -> Maybe a -> b
- const maybe = curry((alt, fn, aMaybe) => aMaybe.isNothing ? alt : fn(aMaybe.$value));
- const prependString = curry((str, val) => `${str} ${val}`);
- // wraps a value in a function, used in places where a function is needed,
- // but you want the value given to the function.
- const returnTheValue = val => val;
- // Allows dot notation instead of array segments as in Ramda's 'path' function
- const elvis = curry((path, object) =>
- path ? reduce((value, key) =>
- value && value[key], object, path.split(".")) : object
- );
- // Wraps elvis in a Maybe Monad so they can't harm him
- const safeElvis = curry((path, object) => Maybe.of(elvis(path, object)));
- const getHeightWrongly = safeElvis("metadata.attributes.BLAH.value");
- const getHeight = safeElvis("metadata.attributes.height.value");
- // composeSuccessMessage :: Maybe m -> string b
- const composeSuccessMessage = compose(prependString("Found a person's height:"), returnTheValue);
- const person = {
- name: 'I am second',
- metadata: {
- attributes: {
- height: {
- value: 23
- }
- }
- }
- };
- const result1 = maybe("Wrong path!", returnTheValue, getHeightWrongly(person)); // Nothing as "Wrong path!"
- const result2 = maybe("Wrong path!", composeSuccessMessage, getHeight(person)); // Just(23) as "Found a person's height: 23"
- console.log(result1);
- console.log(result2);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement