Click here to Skip to main content
15,884,936 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hello to everyone
Can anybody explain how can I count both the total number and the number of unique operators and operands in a JavaScript program?
thanks
Posted

You have to somehow parse the JavaScript source code, in order to extract such a info.
You may have a look at existing parsers (Google is your friend[^]).
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 28-Oct-15 10:46am    
5ed. Please see Solution 2 where I explain how to get script text, so you could have something to parse the code... :-)
—SA
In addition to Solution 1, here is a hint for you: you can get the code of your script in the same script.
For starters, here is how you can get the code of some function in a string:
JavaScript
function A(a, b) { /* some function implementation here */ }

var codeOfA = A.toString(); // now you can parse your string the way you want

Moreover, you can get the full text of some script, as an element of the HTML page. This is how:
JavaScript
var scripts = document.getElementsByTagName("script");
for (var index = 0; index < scripts.length; ++index) {
	var scriptText = scripts[index].text;
	// parse scriptText...
}

Note that the script should be embedded in the HTML where you are using your script; if the script is in some separate file, its text property returns empty string.

—SA
 
Share this answer
 
v2
Comments
CPallini 28-Oct-15 10:48am    
Interesting.
Script languages are strange and powerful beasts.
5.
Sergey Alexandrovich Kryukov 28-Oct-15 10:50am    
Oh yes. And JavaScript has been dubbed the most misunderstood language in the world, which I tend to agree with.
Thank you, Carlo.
—SA
Dzianis Igaravich Leanenka 28-Oct-15 11:01am    
Thank you a lot, I appreciate it.
Sergey Alexandrovich Kryukov 28-Oct-15 11:26am    
You are welcome.
Will you accept the answer formally then?
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900