如何优化用于计算代码行的算法?

时间:2019-05-28 18:10:20

标签: javascript reactjs redux

我创建一个计算Github存储库中代码行数的应用程序。用户输入到存储库的链接,然后出现一个表,该表由以下几列组成:“文件名”,“总计”,“代码”,“注释”,“空”。

我的算法有效,但是当开始处理大文件时,页面冻结。您能告诉我如何优化此算法吗?

fetch(....).then(result => {
                if (itmes.type==='file'){
                const content = Buffer.from(result.data.content, 'base64').toString();
                CountCode(content);
                }


                  //content is string
 function CountCode(content) {

        console.log('processing');

        //Count total
        let lines = content.split(/\r|\r\n|\n/);
        let total_lines = lines.length;

        //Count comments like /* */
        let comment = content.replace(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/g,"");
        let comment2 = comment.split(/\r|\r\n|\n/);
        let comment_lines = total_lines - comment2.length;
        console.log(comment_lines);

        //Count comments like //
        let comment3 = content.replace(/^[/][/].*/gm,"");
        let comment4 = comment3.split(/\r|\r\n|\n/);
        let comment_lines2 = total_lines - comment4.length;
        console.log(comment_lines2);

        //Count Total lines
        let total_comment_lines=comment_lines+comment_lines2;
        console.log(total_comment_lines);
        //Count empty lines//
        let empty = content.replace(/^\s*$/gm,"");
        let empty2 = empty.split(/\r|\r\n|\n/);
        let total_empty= total_lines - empty2.length;
        console.log(total_empty);
        //Count Total Code
        let total_code = total_lines - total_empty - total_comment_lines;
        console.log(total_code);

        console.log('TOTAL: '+total_lines+'  COMMENT: '+total_comment_lines+ ' EMPTY: '+ total_empty+ ' CODE: '+ total_code);
    }

0 个答案:

没有答案