npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

cyclomatic-js

v1.1.5

Published

A library to provide the Cyclomatic Complexity analysis of Vanilla JS source files

Downloads

14

Readme

CyclomaticJS - A Complexity Measure for JavaScript

Cyclomatic Complexity was developed by a Computer Scientist at IBM named Thomas McCabe in an article titled A Complexity Measure. A metric we often use to identify "code quality" concerns, cyclomatic complexity is a useful analytical tool for many reasons. And now it's available for both CommonJS and ESModules JavaScript repositories!

First, let's cover the technical How-To for the contained NPM package and it's GitHub Action. Second, we'll dive deep into theory and explain why you would even want to use this anyway.

Using

You can levarage CyclomaticJS as both a standalone import for your JavaScript project or as a GitHub Action in your CI workflows.

CyclomaticJS as an Import

CyclomaticJS provides a library for importing into JS:

import {calculateComplexity} from 'cyclomatic-js'

const complexity = calculateComplexity('somefile.js')
console.log(complexity)

This will produce a file called complexity-report.json in the main directory of your repository. The file will loo like this:

[
  {
    "file": "./src/some-file.js",
    "report": {
      "function1": 2,
      "function2": 1,
      "function3": 3
    }
  }
]

The report object is simple, it contains the filename and a report with the function name and the cyclomatic complexity for that function.

CyclomaticJS as a GitHub Action

CyclomaticJS also provides a GitHub Action to generate a report for pushing to any BI tool or storage for aggregation and analysis:

- name: Generate Code Metrics for Commit
  id: metrics
  uses: offgriddev/cyclomatic-js-action@main
  with:
    github_token: ${{ github.token }}
    event: ${{ toJson(github.event) }}
    includedFileTypes: .js$
    excludedFileTypes: __mocks__|.test.js|Test.js|dist

This action has one export: export_filename. This stores the filename for the report generated by the complexity reporter in the CyclomaticJS package.

Why Use CyclomaticJS?

To answer why you would want to use CyclomaticJS, you need to know a little about the code metric it uses. You may be new to software engineering, or you might be a senior or director and have not thoughtfully understood this concept. So let us briefly cover its nature.

What is Cyclomatic Complexity

Cyclomatic Complexity, the code metric this repository analyses, measures the number of linear paths through a given function. Your function may be simple:

function getNumberPolarity(a) {
  if (a > 0) {
    return 'is positive'
  } else if (a < 0) {
    return 'is negative'
  } else {
    return 'is neither positive nor negative'
  }
}

But as you can see, given a specific range of the variable a, the output may be different. There are three possible outputs.

  1. When a > 0, the output is is positive.
  2. When a < 0, the output is is negative.
  3. When a == 0, the output is is neither positive nor negative.

Since there are 3 possible paths through this function, the Cyclomatic Complexity is 3. This is acquired by creating an Abstract Syntax Tree and measuring the logical structures of a function. An IfStatement, for example, increases the Cyclomatic Complexity of the function because it creates a logical branch in it. The lowest possible number of logical branches in a given function is 1 as an empty BlockStatement, or function empty() { } has one logical branch.

Logical Structures that Increase Complexity

These logical structures are Universal. Any Turing Complete language can be measured by its logical structures. The following statements and expressions unconditionally increase the complexity of a function:

IfStatement TryStatement CatchClause DoWhileStatement ForInStatement ForOfStatement WhileStatement ConditionalExpression

The following conditionally increase the complexity of a function:

SwitchCase as in the case statement of a SwitchStatement increases the complexity when the case has statements. LogicalExpression increases the complexity when it is a ||, &&, or ??.

Why Use Cyclomatic Complexity

Now for the question you may have asked yourself at some point if you've made it this far and have been looking for a JavaScript library to do this analysis for you. There are two main personas this library and action are targetting: Developers and anyone concerned with estimations. That last persona is vague. I promise, I will get there.

From a developer perspective, you may be concerned with Code Quality and Maintainability. You may have linting rules setup to limit the "size" if your functions, e.g. eslint-complexity. Some developers have a genuine interest in this as an engineering concern, and rightfully so. This may be around modularization and the role of writing more simple and elegant functions.

If you don't believe Cyclomatic Complexity or nerd out on analysing the logical complexity of your code, then you may be concerned about Estimations in some sense. You might be a Project Manager, a Lead Engineer, or perhaps you work in Professional Services and are putting a bid on a job and want to be competitive and realistic.

That's right, you might want to give a realistic estimation for a given software development effort. You might, for example, be the CTO and need to report to ELT a high-level estimate for getting funding for a project. The second category is broad, but you want to provide as realistic of an estimation as you can.

Estimation Methodology

Code is complex. Complexity in our functions is a result of the logical structure we write. When we develop, we produce functions, algorithms, that codify business requirements. If we take snapshots of this over time, we can understand the pace at which we develop software. Therefore, we can provide realistic estimations based on the concrete code we deliver over time.

This repository allows your teams to analyze the comlexity you're deliver as part of codifying the business requirements in your repositories. Complexity grows over time. Each developer also delivers functions of a given complexity at some rate. Cyclomatic Complexity is the objective measurement you can use the give estimations. By measuring the complexity a developer commits to production, you can do the following:

  1. The actual complexity delivered by getting the delta from the previous commit
  2. Validate the accuracy of an estimate
  3. Understand the rate a developer produces business requirements based on the developer's historic delivery of functional complexity

Supported Source Code

CyclomaticJS supports both CommonJS and ESModules. Please raise an issue if there are problems with either module loading systems.