[Javascript Crocks] Recover from a Nothing with the `alt` method

Once we’re using Maybes throughout our code, it stands to reason that at some point we’ll get a Maybe and want to continue applying transformations. We might get a Nothing and want to perform those same transformations on some default value. In this lesson, we’ll do exactly that! We’ll see how we can use the alt method on the Maybe to recover from a Nothing and continue applying transformations with a Just.

const crocks = require('crocks')
const { and, compose, isEmpty, isString, Maybe, not, prop, safe } = crocks
const { join, split, toLower } = require('ramda')


const article = {
    id: 1,
    name: 'Learning crocksjs functional programming library'
};

const createUrlSlug = compose(join('-'), split(' '), toLower);
const createUrl = slug => `https://egghead.io/articles/${slug}`;
const createUrlFromName = compose(createUrl, createUrlSlug);
const isNonEmptyString = and(not(isEmpty), isString);


const getArticleName = obj => prop('name', obj)
    .chain(safe(isNonEmptyString)) // If return Nothing then use alt value
    .alt(Maybe.of('page not found'));

const getArticleUrl = obj => getArticleName(obj)
    .map(createUrlFromName)
    .option('default');

const url = getArticleUrl(article);

console.log(url)

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/9037350.html