Uncurry ramdajs 函数
Uncurry ramdajs function
我有以下数据结构:
const cluster = {
processes: [
{ color: 'test', x: 0, y: 0 },
...
],
};
现在我想使用以下符号来创建函数:
// getProcess :: (Cluster, number) -> Process
getProcess(cluster, 0);
// => { color: 'test', x: 0, y: 0 }
好吧,我尝试为此使用 ramdajs:
const getProcess = R.compose(R.flip(R.nth), R.prop('processes'));
它对 getProcess(cluster)(0)
工作正常,但对 getProcess(cluster, 0)
它 return 一个函数。
有没有办法用 ramda 解决这个问题或者更正确的实现?
您可以使用 R.uncurryN
来实现这一点,它只需要您想要取消柯里化的参数数量以及柯里化函数。
const getProcess = R.uncurryN(2, R.compose(R.flip(R.nth), R.prop('processes')));
这适用于所有柯里化函数,无论是由 Ramda 生成的还是明确如下所示。
R.uncurryN(2, x => y => x + y)
另一种简洁的写法是使用 R.useWith
,尽管我倾向于发现使用 useWith
的可读性不如其他方法。
const getProcess = R.useWith(R.nth, [R.identity, R.prop('processes')])
getProcess(0, cluster)
有时更直接的方法更可取..
const getProcess = R.curry(
(pos, entity) => R.path(['processes', pos], entity)
);
我有以下数据结构:
const cluster = {
processes: [
{ color: 'test', x: 0, y: 0 },
...
],
};
现在我想使用以下符号来创建函数:
// getProcess :: (Cluster, number) -> Process
getProcess(cluster, 0);
// => { color: 'test', x: 0, y: 0 }
好吧,我尝试为此使用 ramdajs:
const getProcess = R.compose(R.flip(R.nth), R.prop('processes'));
它对 getProcess(cluster)(0)
工作正常,但对 getProcess(cluster, 0)
它 return 一个函数。
有没有办法用 ramda 解决这个问题或者更正确的实现?
您可以使用 R.uncurryN
来实现这一点,它只需要您想要取消柯里化的参数数量以及柯里化函数。
const getProcess = R.uncurryN(2, R.compose(R.flip(R.nth), R.prop('processes')));
这适用于所有柯里化函数,无论是由 Ramda 生成的还是明确如下所示。
R.uncurryN(2, x => y => x + y)
另一种简洁的写法是使用 R.useWith
,尽管我倾向于发现使用 useWith
的可读性不如其他方法。
const getProcess = R.useWith(R.nth, [R.identity, R.prop('processes')])
getProcess(0, cluster)
有时更直接的方法更可取..
const getProcess = R.curry(
(pos, entity) => R.path(['processes', pos], entity)
);