SLOC

Calculate source lines of code (SLOC) incrementally.

Usage

var incrsloc = require( '@stdlib/_tools/static-analysis/js/incr/sloc' );

incrsloc()

Returns an accumulator function for incrementally calculating source lines of code (SLOC).

var accumulator = incrsloc();

accumulator( [input] )

If provided an input program, the accumulator function returns an updated source lines of code (SLOC) statistical summary. If not provided an input program, the accumulator function returns the current SLOC summary state. The input program may be either a string or a Buffer.

var sloc = accumulator();
// returns {}

sloc = accumulator( 'var x = 5;' );
// returns {...}

sloc = accumulator( 'var y = foo( 3.14 );' );
// returns {...}

sloc = accumulator( 'if ( x < y ) {\n\tconsole.log( "x < y" );\n}\n' );
// returns {...}

sloc = accumulator();
/* e.g., returns
  {
    "count": 3,        // number of programs
    "min": 1,          // minimum SLOC in a program
    "max": 3,          // maximum SLOC in a program
    "range": 2,        // max - min
    "midrange": 2,     // (max-min)/2
    "sum": 5,          // total SLOC
    "mean": ~1.67,     // average SLOC per program
    ...
  }
*/

Notes

  • Source lines of code (SLOC) is defined as the total number of program lines, excluding empty lines (which includes lines containing only whitespace) and lines containing only comments. When calculating SLOC, analysis assumes specific stylistic forms. For example, analysis does not distinguish between "verbose" if statements and if statement shorthand, always opting for the verbose form.

    var x = -5.0;
    
    // Shorthand:
    if ( x < 0.0 ) x *= -1;
    
    // "Verbose":
    if ( x < 0.0 ) {
        x *= -1;
    }
    
  • For further details regarding how SLOC is calculated, see program-summary.

  • For each input program, the accumulator function generates a program summary for that program. Upon generating a program summary, the accumulator extracts SLOC results and updates the accumulator state.

  • If provided a malformed input program, the accumulator will throw an Error.

  • Summary statistics are computed via incrsummary.

Examples

var incrsloc = require( '@stdlib/_tools/static-analysis/js/incr/sloc' );

var prog;
var acc;

// Initialize an accumulator:
acc = incrsloc();

// Analyze a series of programs:
prog = 'var x = 5;\n';
acc( prog );

prog = 'var y = "beep";\n';
acc( prog );

prog = 'var z = {\n"foo": "bar"\n};\n';
acc( prog );

prog = 'function add( x, y ) {\n\treturn x + y;\n}\n';
acc( prog );

prog = 'for ( i = 0; i < 5; i++ ) {\n\tconsole.log( i );\n}\n';
acc( prog );

prog = 'if ( x < y ) {\n\tconsole.log( "x < y" );\n} else {\n\tconsole.log( "x >= y" );\n}\n';
acc( prog );

// Print the current state of the accumulator:
console.log( JSON.stringify( acc() ) );