以下RAMDA/功能编程模式是否遵循公约/最佳实践



原始

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版本是否遵循公约/最佳实践?

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

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

从最佳实践的角度来看,您的"功能"版本是否还可以,因为这主要是主观的辩论。

我唯一能说的是,无点样式 can 可以通过将东西分成较小的块来减轻它:

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

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

最新更新