学习 TypeScript 泛型排序

28 阅读1分钟

使用 TypeScript 实现的一个通用冒泡排序算法,该实现展示了 TypeScript 的多个高级特性的使用,包括泛型、接口、类和静态方法等。

案例:创建一个人物列表排序人物的身高

技术特性

  • TypeScript 泛型(Generics)
  • 接口(Interface)
  • 类(Class)
  • 静态方法(Static Method)
  • 私有属性(Private Properties)
  • 访问器(Getter)

核心代码结构

1. Person 类

class Person {
  private _name: string; // 姓名
  private _salary: number; // 身高
  
  constructor(name: string, salary: number) {
    this._name = name;
    this._salary = salary;
  }
  
  get name() {
    return this._name;
  }
  
  // 对比两个人的身高
  public static Compare(e1: Employee, e2: Employee): boolean {
    return e1._salary < e2._salary;
  }

  public ToString(): string {
    return this._name + ':' + this._salary;
  }
}

特点:

  • 使用私有属性 _name_salary 实现数据封装
  • 提供 name getter 方法访问私有属性
  • 实现静态比较方法 Compare 用于排序
  • 实现 ToString 方法用于格式化输出

2. 通用比较方法接口

interface method<T> {
  (e1: T, e2: T): boolean
}

特点:

  • 使用泛型定义通用比较方法接口
  • 接受两个相同类型的参数并返回布尔值
  • 可用于任何类型的比较操作

3. 通用排序算法

function CommonSort<T>(sortArray: T[], compareMethod: method<T>): void {
  for (let i: number = 0; i < sortArray.length - 1; i++) {
    for (let j: number = 0; j < sortArray.length - 1 - i; j++) {
      if (compareMethod(sortArray[j], sortArray[j + 1])) {
        const temp: T = sortArray[j];
        sortArray[j] = sortArray[j + 1];
        sortArray[j + 1] = temp;
      }
    }
  }
}

特点:

  • 实现泛型冒泡排序算法
  • 接受任意类型数组和对应的比较方法
  • 通过比较方法实现不同类型的排序逻辑

使用示例

function main(): void {
  const sortArray: Person[] = [
    new Person('司马懿', 190),
    new Person('陈登', 160),
    new Person('王亮', 160),
    new Person('诸葛亮', 192),
    new Person('郭嘉', 152),
    new Person('荀彧', 156)
  ];

  CommonSort<Person>(sortArray, Person.Compare);
  sortArray.forEach(element => {
    console.log(element.ToString());
  });
}