TS实现按文件名称排序效果

311 阅读1分钟
  1. 比较字符串里的第一位,判断其类型。
  2. 如果类型不一致,进行排序(遵循特殊字符 > 数字 > 字母 > 汉字)。
  3. 如果类型一致,判断值是否相等。若不等,则通过localeCompare方法比较。若相等,则进行下一位的比较(再到步骤1,判断类型),直至字符串的最后一位(name1, name2字符串取最小长度),若仍相等,则再通过localeCompare方法比较

代码如下

function sortLikeWin(name1:string, name2:string) {
  const regexPunc = /[\s!!#$%&(()),,、.。;;?@[\]^_`{}~‘’“”《》¥【】+=·…]/
  const regexNum = /[0-9]/
  const regexEng = /[A-Za-z]/
  const regexCh = /[\u4E00-\u9FFF]/
  // 排序大小: 特殊字符 > 数字 > 字母 > 汉字
  // 如果第一个字符相等,再比较下一个字符
  let compareValue = 0
  const minLength = Math.min(name1.length, name2.length)
  let i = 0
  do {
    const aIndex = name1.charAt(i)
    const bIndex = name2.charAt(i)
    const nameFirstType = [aIndex, bIndex].map((item) => {
      if (item.match(regexPunc)) {
        return 0
      }
      if (item.match(regexNum)) {
        return 1
      }
      if (item.match(regexEng)) {
        return 2
      }
      if (item.match(regexCh)) {
        return 3
      }
      return -1
    })
    // 如果第一个字符不相等
    if (aIndex !== bIndex) {
      if (nameFirstType[0] !== nameFirstType[1]) {
        compareValue = nameFirstType[0] - nameFirstType[1]
        break
      } else {
        // 中文需根据拼音顺序
        compareValue = aIndex.localeCompare(bIndex, 'zh')
        break
      }
    }
    if (i === minLength) {
      compareValue = name1.localeCompare(name2, 'zh')
      break
    }
    i += 1
  } while (i <= minLength)
  return compareValue
}