Smelly Code

Insertion Sort with Callback.

May 16, 20171 min 👓

interface SortCallback {
  (a: any, b: any): boolean;
}
class InsertionSort {
  private sortCb(a, b): boolean {
    return a > b;
  }
  public sort(array, cb: SortCallback = this.sortCb) {
    for (let i = 1; i < array.length; i++) {
      let j = i - 1;
      let key = array[i];
      while (j >= 0 && cb(array[j], key)) {
        array[j + 1] = array[j];
        array[j] = key;
        j -= 1;
      }
    }
  }
}
let iSort = new InsertionSort();
let array = [5, 2, 4, 6, 1, 3];
console.log(JSON.stringify(array));
iSort.sort(array, (a, b) => b > a);
console.log(JSON.stringify(array));

Hitesh

Hi, I am Hitesh.

|