日常工具1-代码review之鉴 山

312 阅读2分钟

开篇

大家都是如何代码review的?看代码质量?函数复杂度?响应效果?算了这些在屎山面前都不值一提,今天就教大家如何快速鉴 屎·山

如何快速鉴山?

山,汉语一级字,读作shān,最早见于金文 [1]**,其本义是地面上由土石构成的隆起的部分,因为山是高耸的而引申出“大”的含义,又引申出坟墓、隐居之处等含义。《说文解字》认为是“宣也”。

代码中=单个文件行数较长

代码实现

主要使用fs

# 主要函数

async function get_count_from_folder(folderPath) {
  let totalLines = 0;
  const files = fs.readdirSync(folderPath);

  for (const file of files) {
    const fullPath = path.join(folderPath, file);
    const stats = fs.statSync(fullPath);

    if (!exclude(file)) {
      console.log(file, "folder in exclude");
    } else {
      if (stats.isDirectory()) {
        const subfolderLines = await get_count_from_folder(fullPath);
        totalLines += subfolderLines;
      } else if (stats.isFile()) {
        if (!excludes_name.includes(file)) {
          const lines = await get_count_from_file(fullPath);
          //TODO analysis
          if(lines>500){
            console.log(`${fullPath}-------: ${lines} lines`);
          }
          totalLines += lines;
        }
      }
    }
  }

  return totalLines;
}

# 可配置过滤一些具体的文件名以及文件夹名

function exclude(file, name) {
  const excludes = [
    "node_modules",
    "dist",
    "public",
    "style",
    ".vscode",
    ".git",
    "assets",
    ".husky",
  ];
  return !excludes.includes(file);
}
const excludes_name = ["yarn.lock", "package-lock",'EBML.js'];

# 如何计算单个文件的行数
function get_count_from_file(filePath) {
  return new Promise((resolve, reject) => {
    let lineCount = 0;
    const stream = fs.createReadStream(filePath);
    stream.on("data", (buffer) => {
      let idx = -1;
      while ((idx = buffer.indexOf(10, idx + 1)) >= 0) {
        lineCount++;
      }
    });
    stream.on("end", () => resolve(lineCount));
    stream.on("error", reject);
  });
}

# 使用
(async () => {
  const eq = "E://work//path";
  if (!fs.existsSync(eq)) {
    console.error("Folder does not exist");
    return;
  }

  const totalLines = await get_count_from_folder(eq);
  console.log(`Total lines: ${totalLines}`);// 获取你项目有效行数
})();


结果

image.png 找到了山,超过500行的文件,你点进去看肯定是山,当然是不是屎还得继续分析。直觉发现 屎 山 不分家。

总结

代码水平有差异不重要,该拆分的拆分。不要堆山。真的难绷。

如何鉴屎?想了几个维度,大家也可留言交流

  • 以vue为例检索对象或者字符串出现次数,本项目中一个文件里某个对象出现212次
  • 单个函数长度