以下 Ramda/function 编程模式是否遵循 conventions/best 实践?

Does the following Ramda/function programming pattern follow conventions/best practices?

原创

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

拉姆达

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/functional 编程版本感觉很冗长,但我不太明白如何让它更优雅。就目前而言,original/imperative 版本似乎更容易 read/understand。我的 Ramda 版本是否遵循 conventions/best 惯例?

个人觉得你原来的功能还是不错的。由于您使用的是 ES6,因此您可以摆脱(命令式的)return 语句:

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

从最佳实践的角度来看,您的 "functional" 版本是否合适很难说,因为这主要是一场主观辩论。

我唯一能说的是,无点风格 可以 导致冗长,但你可以通过将事情分成更小的块来减轻它:

例如,这对您来说会更好吗?

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']));