how could I reduce the cyclomatic complexity?

后端 未结 5 2161
感情败类
感情败类 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:20

    Bergi has already given a correct answer, but it's still too complex for my taste. Since we're not using fortran77 I think we're better off using an early return. Also, the code may be further clarified by introducing extra variables:

    function doSomething(isScrolling, start, delta, viewport) {
        if (isScrolling) return;
    
        var duration = +new Date() - start.time;
        var isPastHalf = Number(duration) < 250 && Math.abs(delta.x) > 20 || Math.abs(delta.x) > viewport / 2;
        var isFarRight = this.content.getBoundingClientRect().left > viewport / 2;
    
        // I'm not sure if my variable names reflect the actual case, but that's
        // exactly the point. By choosing the correct variable names for this,
        // anybody reading the code can immediatly comprehend what's happening.
        var isMovingToLeft = delta.x < 0;
        var isMovedPastEnd = isPastHalf && !isMovingToLeft && !(isFarRight && pulled);
        var isMovedBeforeStart = !isPastHalf && isMovingToLeft && isFarRight;
    
        if (isMovedPastEnd || isMovedBeforeStart) {
            this.open();
        else
            this.close();
        }
    } 
    

提交回复
热议问题