I would like to find a way to re-use a sort function in Typescript when I have different kinds of objects or types if possible. Unfortunately, because I am calling sort with the method itself, I cannot preserve context and things break. For example:
interface A {
num: number
}
class Example {
sortTwoLists():boolean {
let sortList1 = [4,5,3,1,2].sort(this.pinnedSortSample);
let sortList2 = [{num:4} as A, {num:5} as A, {num:3} as A, {num:1} as A, {num:2} as A]
.sort(this.objectpinnedSortSample)
let numsOnly = sortList2.map((x) => x.num)
return numsOnly.length === sortList1.length && numsOnly.every((value, index) => value === sortList1[index])
}
pinnedSortSample(item1:number, item2:number) {
let pins = [3,6]
if (pins.includes(item1) && pins.includes(item2)) {
return pins.indexOf(item1) - pins.indexOf(item2)
} else if (pins.includes(item1)) {
return -1;
} else if (pins.includes(item2)) {
return 1;
} else {
if (item1 < item2) {return -1}
if (item1 > item2) {return 1}
return 0;
}
}
objectpinnedSortSample(item1: A, item2: A) {
let context = this;
return context.pinnedSortSample(item1.num, item2.num);
}
}
const x = new Example().sortTwoLists();
console.log(x);
Returns with the error Cannot read properties of undefined (reading 'pinnedSortSample')
.
Because the sort is longer than your usual sort functions (I gave an example of a pinned sort for reference), it would be nice to refer to other predicates as helpers if possible.
I am currently resolving the problem by just duplicating the code in pinnedSortSample, but I wonder if there is a way to preserve context such that I can refer to the original predicate for other use cases.