在Ramda中编写更高级别的功能

时间:2016-11-30 00:39:42

标签: javascript functional-programming function-composition ramda.js

我急切地想要学习js中的函数式编程,但是我很难过。我觉得我经常做这样的事情,这根本感觉不对:

export const getParamFromUrl = R.curry((name, url) => R.compose(
    R.match(new RegExp(`[?&]${name}=([^&]*)`))
)(url));

我不觉得我应该立即调用compose。那么,用两个算法进行函数合成的正确方法是什么?

编辑:为了清楚起见,这是它看起来的实际功能(我知道这不是获取查询字符串的最佳方式)

/* util.toMaybe takes a function and a value and returns Nothing()
   if the function returns true and Just(value) if it returns false.
   I think this is the HM:
   util.toMaybe :: (a -> Boolean) -> a -> Maybe a
*/
export const getParamFromUrl = R.curry((name, url) => R.compose(
    R.chain(util.toMaybe(R.isEmpty)),
    R.map(R.nth(1)),
    util.toMaybe(R.isEmpty),
    R.match(new RegExp(`[?&]${name}=([^&]*)`))
)(url));

通过接受的答案,这将成为:

export const getParamFromUrl = R.curry(R.compose(
    R.chain(util.toMaybe(R.isEmpty)),
    R.map(R.nth(1)),
    util.toMaybe(R.isEmpty),
    (name, url) => R.match(new RegExp(`[?&]${name}=([^&]*)`), url)
));

1 个答案:

答案 0 :(得分:1)

您对compose电话的意思并不十分清楚。没有它,该功能将同样有效,而且更清晰。

const getParamFromUrl = R.curry((name, url) => 
    R.match(new RegExp(`[?&]${name}=([^&]*)`), url));

如果您打算在合成中添加其他功能,那么您可以这样做:

const getParamFromUrl = R.curry(R.compose(
    nth(1),
    (name, url) => R.match(new RegExp(`[?&]${name}=([^&]*)`), url)
));

请注意,for technical reasonscompose的结果不会自动计算,因此您需要自己做。

您可以在 Ramda REPL 上看到这一点。

相关问题