how could I reduce the cyclomatic complexity?

后端 未结 5 2193
感情败类
感情败类 2021-01-04 01:48

Whenever I lint a piece of code I\'m working on I get the This function\'s cyclomatic complexity is too high. (7). But I\'m a bit confused on how I could rewrit

5条回答
  •  渐次进展
    2021-01-04 02:16

    Actually all those return statements are confusing the issue, but they offer a hint to the solution.

    if (direction) {
      this.close();
    } else {
      if (this.content.getBoundingClientRect().left > viewport / 2 && pulled === true) {
        this.close();
        return; // We'll never `this.open()` if this is true anyway, so combine the booleans.
      }
      this.open();
    }
    

    How about:

    if (direction || (this.content.getBoundingClientRect().left > viewport / 2 && pulled === true)) {
      this.close();
    } else {
      this.open();
    }
    

    And as for:

    if (this.content.getBoundingClientRect().left > viewport / 2) {
      if (this.isEmpty(delta) || delta.x > 0) {
        this.close();
        return; // Combine the booleans!
      }
      this.open();
      return;
    }
    

    Simplify:

    if ((this.isEmpty(delta) || delta.x > 0) || !this.content.getBoundingClientRect().left > viewport / 2) {
      this.close();
    } else {
      this.open();
    }
    

    (Aside: The original post left out a closing brace. If you (OP) intended that the function continues past your post, then this answer is wrong (but you should've made that clearer))

    Result: We've eliminated two (repeated) decisions:

    function () {
      var duration = +new Date() - start.time,
        isPastHalf = Number(duration) < 250 && Math.abs(delta.x) > 20 || Math.abs(delta.x) > viewport / 2,
        direction = delta.x < 0;
    
      if (!isScrolling) {
        if (isPastHalf) {
          if (direction || (this.content.getBoundingClientRect().left > viewport / 2 && pulled === true)) {
            this.close();
          } else {
            this.open();
          }
        } else {
          if ((this.isEmpty(delta) || delta.x > 0) || !this.content.getBoundingClientRect().left > viewport / 2) {
            this.close();
          } else {
            this.open();
          }
        }
      }
    }
    

提交回复
热议问题