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

本文通过重构代码示例,展示了如何使用函数组合来简化针对Maybe类型的系列转换操作,实现可复用的功能处理流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值