[Javascript Crocks] Compose Functions for Reusability with the Maybe Type

We can dot-chain our way to great success with an instance of Maybe, but there are probably cases where you need to apply the same series of transformations against different Maybes. In this lesson, we’ll look at some point-free versions of some common Maybe methods and see how we can compose them together to get a reusable function that can be applied to any Maybe instance.

We are going to rewrite the following code by using function composion:

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)

We can import those instance methods directly:

const { and, compose, isEmpty, isString, Maybe, not, prop, safe, chain, map, alt, option } = crocks
const crocks = require('crocks')
const { and, compose, isEmpty, isString, option, Maybe, not, prop, safe, chain, map, alt } = 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 getArticleUrl = compose(
    option('default'),
    map(createUrlFromName),
    alt(Maybe.of('page not found')),
    chain(safe(isNonEmptyString)),
    prop('name')
);
/*
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/9037945.html