I want to sort an array of object (of the same interface) firstly sorting by one attribute of this interface, if these attributes are equals then sorting by secondly attribute, then sorting by a third attribute and so on. And all in typescript mode.
我尝试的解决办法:
定义:
Sorter = (a: T, b: T) => number;
例:
const stateSorter = (aState: number, bState: number) => (bState < aState? -1 : 1);
const dateSorter = (aDate: Date, bDate: Date) => (aDate >= bDate ? -1 : 1);
1. 围绕T接口的属性界定一个分类器
interface SortSupplier<T, R> { supplier: (container: T) => R; sorter: Sorter< R >; }
例:
interface StateAndDate {
stateId: ClientStateIdEnum;
registrationDate: Date;
}
const sorterBySupplier: SortSupplier<StateAndDate, Date> = {supplier: container => container.registrationDate, sorter: dateSorter}
第一项错误企图:
采用多种优先等级:
const sortBySorters1 = <T>(a: T, b: T, orderedSorters: SortSupplier<T, any>[]): number => {
let sortResult = 0;
orderedSorters.some(supplierSorter => {
类别Result = 供应商Sorter.sorter(supplierSorter.supplier(a),供应商Sorter.supplier(b);
return sortResult !== 0;
});
return sortResult;
}
一个错误的例子就是:
(a: StateAndDate, b: StateAndDate) => {
return sortBySorters1(a, b, [
{supplier: container => container.stateId, sorter: stateSorter},
{supplier: container => container.registrationDate, sorter: stateSorter}
]);
}
之所以错了,是因为第二类人必须按日期分类,但因使用任何作为第二大类的SortSupplier而按数量(国家)接受其他不同类型。
第二次错误企图:
创建各类可能的特性,例如,数字和日期:
type SortSupplierType<T> = SortSupplier<T, Date>|SortSupplier<T, number>;
然后,以前的错误分类组合:
{supplier: container => container.registrationDate, sorter: stateSorter}
给出汇编错误,唯一的合规解决办法是:
(a: StateAndDate, b: StateAndDate) => {
return sortBySorters1(a, b, [
{supplier: container => container.stateId, sorter: stateSorter},
{supplier: container => container.registrationDate, sorter: dateSorter}
]);
}
但:
const sortBySorters2 = <T>(a: T, b: T, orderedSorters: SortSupplierType<T>[]): number => {
let sortResult = 0;
orderedSorters.some(supplierSorter => {
类别Result = 供应商Sorter.sorter(supplierSorter.supplier(a),供应商Sorter.supplier(b);
return sortResult !== 0;
});
return sortResult;
}
但它给出了下一个汇编错误:
序号的标示不能归入“日期”的参数;编号。
类型编号不能划入“日期”和编号。
类型编号不能按日期类型分配。
类别Result = 供应商Sorter.sorter(supplierSorter.supplier(a),供应商Sorter.supplier(b);
¿Someone有一种普遍的解决办法,可以解决围绕 cas式的先天性交错的此类问题?
(为我的英语教授)