码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-05-14 20:44:31      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:val   oge   obj   learn   you   his   cas   directly   str   

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

标签:val   oge   obj   learn   you   his   cas   directly   str   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!