0

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.

Live code is available for this problem.

Ryan Deschamps
  • 351
  • 4
  • 16
  • Yes - that's the solution. I have updated the live code to show the exact solution. More than willing to give you green check if you want to prepare one. – Ryan Deschamps Oct 20 '21 at 19:36
  • 1
    Nah, it's ok, you can accept the duplicate flag. The answers there already explain it well. And I'm not in the mood to write out an answer explaining how `this` works – my brain will explode :) – Wing Oct 20 '21 at 19:43

0 Answers0