You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改partitionFiles函数实现文件名称与类型双重过滤

解决文件分区函数的文件名与扩展名双重校验问题

问题现状

当前的partitionFiles函数仅校验文件名是否匹配支持列表,未同步校验扩展名,导致像Location.png这类符合名称但扩展名无效的文件,会同时出现在pass(有效)和fail(无效)数组中,不符合预期。需要调整逻辑,让pass数组仅保留同时匹配支持名称和有效扩展名的文件,fail数组收集所有不满足任一条件的文件且无重复。

修正方案

核心思路是:先筛选出同时满足两个条件的文件作为有效集合,再从原数组中排除有效集合得到无效集合,同时保留原函数的去重(同一名称仅保留一个文件)需求。

修正后的完整代码

const values = ["SS.csv", "Account.csv", "Location.png", "SS.txt", "Account.docx"]
const supported_names = ["SS", "Account", "Location"]
const SUPPORTED_EXTENSION = 'csv'

const partitionFiles = (values, supported_names) => {
  const pass = [];
  const matchedFiles = new Set(); // 用于去重,避免同一文件重复加入pass

  for (const supportedName of supported_names) {
    const lowerSupportedName = supportedName.toLowerCase();
    for (const file of values) {
      const lowerFile = file.toLowerCase();
      // 同时校验三个条件:名称匹配、扩展名有效、未被加入过pass
      const isNameMatch = lowerFile.includes(lowerSupportedName);
      const isValidExtension = file.endsWith(`.${SUPPORTED_EXTENSION}`);
      if (isNameMatch && isValidExtension && !matchedFiles.has(file)) {
        pass.push(file);
        matchedFiles.add(file);
        break; // 每个支持名称仅匹配一个文件(保留原去重逻辑)
      }
    }
  }

  // 直接过滤原数组,得到不在pass中的所有文件作为无效集合
  const fail = values.filter(file => !pass.includes(file));

  return [pass, fail];
}

const [validFiles, invalidFiles] = partitionFiles(values, supported_names);

console.log(validFiles); // 输出: ["SS.csv", "Account.csv"]
console.log(invalidFiles); // 输出: ["Location.png", "SS.txt", "Account.docx"]

关键改动说明

  • 双重校验逻辑:生成pass数组时,同时判断文件名是否匹配支持列表(不区分大小写),以及文件扩展名是否符合要求(用endsWith替代includes,避免误判文件名中包含扩展名的情况,比如testcsv.txt)
  • 去重优化:用Set记录已加入pass的文件,确保每个符合条件的文件仅被添加一次,保留原函数的去重需求
  • 无效集合简化:移除了单独遍历扩展名的循环,直接通过过滤原数组生成fail集合,避免重复添加同一文件到fail中

内容的提问来源于stack exchange,提问作者user19989236

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 19:55:22