In order to properly sort an array based on assigned keys, I have implemented the ISortPriority interface. Although my sorting algorithm is functioning correctly, I am encountering difficulties when it comes to utilizing the interface.
Here is an example of the test I am conducting:
it('Should sort with multiple keys - Numbers', () => {
const arr = [{name: 'j company', title: 'Software Eng 1', age: 23,company: 'test'}, {name: 'f company', age: 21, title: 'Software Eng 7', company: 'abc'},{name: 'g company', title: 'Software Eng 2', age: 22, company: 'test'}, {name: 't company', age: 24, title: 'Software Eng 3', company: 'test'}];
const keys: ISortPriority<any>[] = [{sortKey: 'age', priority: 1}, {sortKey: 'company', priority: 3}, {sortKey: 'name', priority: 4}, {sortKey: 'title', priority: 5}];
expect(sortArrayByKey(arr, keys)).toEqual([{name: 'f company', age: 21, title: 'Software Eng 7', company: 'abc'}, {name: 'g company', age: 22, title: 'Software Eng 2', company: 'test'}, {name: 'j company', age: 23, title: 'Software Eng 1', company: 'test'}, {name: 't company', age: 24, title: 'Software Eng 3', company: 'test'}]);
});
However, upon calling:
expect(sortArrayByKey(arr, keys))
An error message pops up stating: "Argument of type 'ISortPriority[]' is not assignable to parameter of type '"title" | "name" | "company" | "age"'." when hovering over the "keys" parameter.
Lastly, here are the sorting method and interface that I am employing:
export function sortArrayByKey<T>(ordersArr: T[], sortByKeys: keyof T): T[] {
return ordersArr.sort((a, b) => {
return sortWithKey(a, b, sortByKeys, 0);
});
}
function sortWithKey<T>(a: T, b: T, keys, index: number) {
index = index || 0;
keys = keys.sort((c, d) => (c.priority > d.priority) ? 1 : -1);
const currKey = keys[index].sortKey;
return a[currKey] > b[currKey] ? 1 : (a[currKey] < b[currKey] ? -1 :
sortWithKey(a, b, keys, index + 1));
}
export interface ISortPriority<T> {
priority: number;
sortKey: keyof T;
}