重构条件嵌套if / else语句的{ESLint问题

时间:2017-08-04 13:57:23

标签: javascript if-statement ecmascript-6

我写了一个相当简单的函数来弄清楚高尔夫球手已经完成了哪个洞。我试着这么做"漂亮" ES6功能方式。

在版本1中,我有一些老式的JS。 版本2我认为它最具可读性和优雅性,但ESLint并不喜欢嵌套的三元运算符。 版本3使ESLint感到高兴,但我认为它实际上更难以遵循并需要更多功能。

根据最新的设计模式和现代语法,有更好,更清晰的方法吗?

这是一个JS小提琴: https://jsfiddle.net/pixelwiz/h3r4nv54/2/

const startedPlayingRound = holesPlayed => holesPlayed > 0;

const finishedPlayingRound = holesPlayed => holesPlayed === 18;

const playingFromFirstTee = (startHole, holesPlayed) => (
  startHole === 1 && holesPlayed >= 1 && holesPlayed < 18
);

const wrapAroundLogic = (startHole, holesPlayed) => (
  playingFromFirstTee(startHole, holesPlayed) ? holesPlayed :
    ((startHole + holesPlayed) - 1) % 18
);

const finishedOrNotYetStarted = holesPlayed => (
  finishedPlayingRound(holesPlayed) ? 'F' : ''
);

const getThruV1 = (startHole, holesPlayed) => {
  let thru = '';
  if (startedPlayingRound(holesPlayed)) {
    if (finishedPlayingRound(holesPlayed)) {
      thru = 'F';
    } else if (startHole === 1 && holesPlayed >= 1 && holesPlayed < 18) {
      thru = holesPlayed;
    } else {
      thru = ((startHole + holesPlayed) - 1) % 18;
    }
  }
  return thru.toString();
};

const getThruV2 = (startHole, holesPlayed) =>
  !startedPlayingRound(holesPlayed) ? '' :
  finishedPlayingRound(holesPlayed) ? 'F' :
  wrapAroundLogic(startHole, holesPlayed).toString();

const getThruV3 = (startHole, holesPlayed) => (
  finishedPlayingRound(holesPlayed) || !startedPlayingRound(holesPlayed) ?
    finishedOrNotYetStarted(holesPlayed) :
    wrapAroundLogic(startHole, holesPlayed).toString()
);

  $('#v1').html('V1 Result: ' + getThruV1(10, 12));
  $('#v2').html('V2 Result: ' + getThruV1(10, 12));
  $('#v3').html('V3 Result: ' + getThruV1(10, 12));

0 个答案:

没有答案