以下Ramda /函数编程模式是否遵循惯例/最佳做法?

时间:2019-03-06 08:12:43

标签: javascript functional-programming ramda.js

原始

export const isTimeStrValid = str => {
  return str.length >= 4 && moment(str, ['H:mm', 'HH:mm'], true).isValid();
};

Ramda

export const isTimeStrValid = R.allPass([
  R.pipe(R.length, R.gte(R.__, 4)),
  R.pipe(
    s => moment(s, ['H:mm', 'HH:mm'], true),
    R.invoker(0, 'isValid'),
  ),
]);

Ramda /功能编程版本感觉很冗长,但我不太清楚如何使它变得更优雅。就目前而言,原始/命令性版本似乎更易于阅读/理解。我的Ramda版本是否遵循惯例/最佳做法?

1 个答案:

答案 0 :(得分:4)

我个人认为您的原始功能很好。由于您使用的是ES6,因此可以摆脱(命令)return语句:

export const isTimeStrValid = str =>
  str.length >= 4 && moment(str, ['H:mm', 'HH:mm'], true).isValid();

从最佳实践的角度来看,您的“功能性”版本是否可行还很难说,因为这主要是主观的辩论。

我唯一能说的是,无点式 会导致冗长,但您可以通过将内容分成较小的块来缓解这种情况:

例如,这对您读起来更好吗?

const isTimeStrValid = R.both(isValidString, isValidMoment);

其中isValidStringisValidMoment是可重用的函数:

const isValidString = R.compose(R.lte(4), R.length);
const toMoment = R.curry((strict, formats, datestr) => moment(datestr, formats, strict));
const isValidMoment = R.compose(R.invoker(0, 'isValid'), toMoment(true, ['H:mm', 'HH:mm']));