首页 > 编程语言 > 详细

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

时间:2018-05-14 20:40:54      阅读:191      评论:0      收藏:0      [点我收藏+]

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)

 

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

原文:https://www.cnblogs.com/Answer1215/p/9037945.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!