I want to work out the number of statements inside a block of javascript code. This is to evaluate how short the code is for a programming challenge (if there's a better/easier way to evaluate code, I'm interested in hearing that too).
For the purposes of this evaluation, I would like to assume a statement is anything that is capable of performing an operation within it, for example:
let values = ['test 1', 'test 2'];
for(let i in values) {
let object = {
a: i%3,
b: Math.floor(i/3),
c: i*2
};
let another = {test: 0 || 4};
let something = values[i];
let otherSomething = getSomeValues(object[a], object[b]);
setSomeValues(object[a], object[c]);
for(let j = 0; j < 5; i++) if(i < j) break;
}
There's quite a lot of syntax to cover so ideally I would like to do this with a library if one is available - my Googling was unable to find anything very suitable.
I tried writing a regex to match all possible breaks between statements, but this is getting messy quickly:
[\n;]|\)[ \w]|[{,][\s\w]+:\s*|[{}]
Here's a link to the regexr I've been using. Breaking this down:
[\n;]
- matches a newline or semicolon, the normal ways to start a new statement\)[ \w]
- matches statements following a closing bracket, e.g.if (something) return;
[{,][\s\w]+:\s*
- matches the key of a key-value pair in an object[{}]
- matches opening and closing brackets of blocks
I also remove any zero-length matches as statements cannot be empty.
As I've said, ideally I would prefer a library but I wanted to ask for some opinions on my approach and if I've got most of the edge cases.