1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| import { orderBy, orderByDescending, SortDirection } from './OrderBuilder';
interface Person { id: number; name: string; age: number; salary: number; department: string; }
const people: Person[] = [ { id: 1, name: "张三", age: 30, salary: 10000, department: "技术部" }, { id: 2, name: "李四", age: 25, salary: 8000, department: "市场部" }, { id: 3, name: "王五", age: 30, salary: 12000, department: "技术部" }, { id: 4, name: "赵六", age: 25, salary: 9000, department: "人事部" }, { id: 5, name: "钱七", age: 35, salary: 15000, department: "技术部" }, { id: 6, name: "孙八", age: 28, salary: 11000, department: "市场部" }, { id: 7, name: "周九", age: 35, salary: 14000, department: "人事部" }, { id: 8, name: "吴十", age: 28, salary: 13000, department: "技术部" }, ];
console.log("示例1: 按年龄升序,然后按薪资降序排序"); const result1 = orderBy(people, p => p.age) .thenByDescending(p => p.salary) .toArray();
console.table(result1);
console.log("\n示例2: 按部门升序,然后按年龄降序,最后按姓名升序排序"); const result2 = orderBy(people, p => p.department) .thenByDescending(p => p.age) .thenBy(p => p.name) .toArray();
console.table(result2);
console.log("\n示例3: 按薪资降序排序"); const result3 = orderByDescending(people, p => p.salary).toArray();
console.table(result3);
console.log("\n示例4: 性能测试"); const generateLargeDataset = (size: number): Person[] => { const departments = ["技术部", "市场部", "人事部", "财务部", "行政部"]; const names = ["张", "李", "王", "赵", "钱", "孙", "周", "吴", "郑", "陈"]; return Array.from({ length: size }, (_, i) => ({ id: i + 1, name: names[Math.floor(Math.random() * names.length)] + (i + 1), age: 20 + Math.floor(Math.random() * 40), salary: 5000 + Math.floor(Math.random() * 15000), department: departments[Math.floor(Math.random() * departments.length)] })); };
const largeDataset = generateLargeDataset(10000);
console.time("排序10000条数据"); const result4 = orderBy(largeDataset, p => p.department) .thenBy(p => p.age) .thenByDescending(p => p.salary) .toArray(); console.timeEnd("排序10000条数据");
console.log(`排序后的前5条数据:`); console.table(result4.slice(0, 5));
|