Ajay Biswas
Ajay Biswas

Reputation: 39

How to count number of function inside a file in javascript

I am new to programming and I came across a question where I am not able to build its logic. In question, I have to count the number of functions present inside a js file. I tried to use fs.readFile method to read the content of a file. As a function can be written in many ways, for eg:

  1. function fun(){}
  2. const fun = (){} (const keyword can also be used for variables)
  3. member of an object
  4. arrow function
  5. anonymous function (both normal and arrow function)

So, I am not getting how can I identify all these types inside a file. Can someone help me in distinguishing all functions from others?

var fs = require("fs")

function task14(pathToFile){
    return new Promise((resolve, reject)=>{
        fs.readFile(pathToFile,"utf8", (error, content)=>{
            if(error)
                reject("Error reading file");
            else{
                let functionCount=0, variableCount=0;
                var arrOfContent = content.split(" ")
               arrOfContent.forEach(a=>{
                    if(a == "let" || a == "var" || a == "const")
                        variableCount++;
                    else if(a == "function" || a == "=>")
                        functionCount++;
                })
                 resolve({
                     functionCount : functionCount,
                     variableCount : variableCount
                 })     
            }

        })
    }
    )}

Upvotes: 1

Views: 1157

Answers (2)

szatkus
szatkus

Reputation: 1395

I wouldn't count this just using text. I could put a code like //() => () and you program would count it.

Use something like https://esprima.org/ to parse the code and count how many Function tokens are there.

Upvotes: 1

PRASANNAKUMAR JHA
PRASANNAKUMAR JHA

Reputation: 11

const fs = require("fs");

const fetchData = (filePath) =>{
    return new Promise((resolve,reject) =>{
        fs.readFile(filePath,"utf8",(err,data)=>{
            if(err)
            reject("Error reading file");
            else{
                console.log("Data::",data);
                var countVar  = 0;
                var countFun = 0;
                var arr1 = data.split("function");
                var arr2 = data.split("() =>");
               var arr3=data.split(" ");
               for(var i=0;i<arr3.length;i++){
                   if(arr3[i] == "let" || arr3[i] == "var" || arr3[i] == "const")
                    countVar++;
               }
               countVar = (countVar+arr2.length-2);
               var countFun = ((arr1.length-1)+(arr2.length-1));
                var ans = {
                    functionCount :countFun,
                    variableCount :countVar
                }
                resolve(ans);
            }
        })
    })
}
module.exports  = fetchData;

Upvotes: 1

Related Questions