UNPKG

xxm-test-js

Version:
90 lines 3.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.sortArray = sortArray; function sortArray(array, order = 'asc', field = null, numericStrings = false) { // 辅助:尝试将未知值解析为数字,失败返回 null const toNumber = (v) => { if (typeof v === 'number') return v; if (typeof v === 'string') { const s = v.trim(); if (s === '') return null; const n = Number(s); return Number.isNaN(n) ? null : n; } return null; }; // 辅助:安全获取对象字段值(不使用 any) const getField = (obj, key) => { if (key === null) return obj; if (obj !== null && typeof obj === 'object') { return obj[key]; } return undefined; }; return array.sort((aa, bb) => { const a = aa; const b = bb; let comparison = 0; if (field === null) { // 普通数组排序 if (numericStrings) { const aNum = toNumber(a); const bNum = toNumber(b); if (aNum !== null && bNum !== null) { comparison = aNum - bNum; } else if (typeof a === 'string' && typeof b === 'string') { comparison = a.localeCompare(b); } else { comparison = String(a).localeCompare(String(b)); } } else { if (typeof a === 'number' && typeof b === 'number') { comparison = a - b; } else if (typeof a === 'string' && typeof b === 'string') { comparison = a.localeCompare(b); } else { comparison = String(a).localeCompare(String(b)); } } } else { // 对象数组,根据字段进行排序(使用 unknown/Record 替代 any) const aValue = getField(a, field); const bValue = getField(b, field); if (numericStrings) { const aNum = toNumber(aValue); const bNum = toNumber(bValue); if (aNum !== null && bNum !== null) { comparison = aNum - bNum; } else if (typeof aValue === 'string' && typeof bValue === 'string') { comparison = aValue.localeCompare(bValue); } else { comparison = String(aValue).localeCompare(String(bValue)); } } else { if (typeof aValue === 'number' && typeof bValue === 'number') { comparison = aValue - bValue; } else if (typeof aValue === 'string' && typeof bValue === 'string') { comparison = aValue.localeCompare(bValue); } else { comparison = String(aValue).localeCompare(String(bValue)); } } } return order === 'asc' ? comparison : -comparison; }); } //# sourceMappingURL=sortArray.js.map