2

I'm reading a book about testable JS and there is a chapter about Cyclomatic complexity, but it doesn't really tell how to calculate it. It just says that

Cyclomatic complexity is a measure of the number of independent paths through your code.

And it gives this example stating that it has cyclomatic complexity of 2:

function sum(a, b) {
    if (typeof(a) !== typeof(b)) {
        throw new Error("Cannot sum different types!");
    } else {
        return a + b;
    }
}

Hence I'm wondering whether this made up example has a cyclomatic complexity of 3:

function madeup(a) {
    if (typeof(a) === "string") {
        if (a === "some") {
            console.log("is a some");   
        } else {
            console.log("not a some");
        }
    } else {
        console.log("not a string");
    }
}

And this of 4:

function madeup(a) {
    if (typeof(a) === "string") {
        if (a === "some") {
            console.log("is a some");   
        } else {
            console.log("not a some");
        }
    } else {
        if (a === 5) {
            console.log("is a 5");  
        } else {
            console.log("not a 5");
        }
    }
}

?

AbcAeffchen
  • 14,400
  • 15
  • 47
  • 66
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488

2 Answers2

1

Yes, you counted correctly. I think that's about all that can be said.

If you're unsure, you can drop your function into http://jshint.com, and it will tell you what the cyclomatic complexity is.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
0

In the first example, the "throw new Exception" and the RETURN statements cause the method to end and all variables to fall out of scope.

The methods in the second and third examples both terminate after the last line in the code. The second and third methods only exit the code in one place, the last line.

If you had a RETURN statement after the console.log methods, then you would have been correct.

As it stands, the Cyclomatic complexity is 1 for examples two and three.