gpt4 book ai didi

javascript - Ramda 中具有更高参数的组合函数

转载 作者:行者123 更新时间:2023-12-03 05:32:38 28 4
gpt4 key购买 nike

我很想学习 js 中的函数式编程,但是我遇到了困难。我觉得我一直在做这样的事情,这感觉根本不对:

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

我觉得我不应该立即调用 compose。那么,进行数量为 2 的函数组合的正确方法是什么?

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

/* 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)
));

最佳答案

目前还不清楚您要对 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 的结果不会自动柯里化(Currying),因此您需要自己执行此操作。

您可以在 Ramda REPL 上看到此操作的实际效果。

关于javascript - Ramda 中具有更高参数的组合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40878357/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com