【发布时间】:2017-04-14 04:27:09
【问题描述】:
我急切地想学习 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)
));
【问题讨论】:
-
也许我没有得到功能方面的东西。你需要马上咖喱吗?像
(name, url) => url.match(new RegExp())[1]这样的常规函数有什么问题,您以后可以随时包装/咖喱该函数,对吧? -
这也是一种非常不可靠的URL参数解析方式
标签: javascript functional-programming function-composition ramda.js