Team Ai
Apppublic

exbert-project/exbert

sourceHugging Faceapache-2.0updated 3y agoView on Hugging Face
185likes
arrayUtils.ts42 linesDownload Raw Back to etc
1// [[val, ind], [val, ind]...]2type CompFnInd = (a:number[], b:number[]) => number;3 4export interface SortArray {5    arr: number[],6    sortIndices: number[],7}8 9/**10 * Copies and sorts an array while keeping track of the indices. Currently only supports sorting max -> min.11 * 12 * @param arr - Array to be copied and sorted13 */14export function sortWithIndices(arr:number[], fn?:CompFnInd): SortArray {15    // If fn is not provided, default to sorting by max value16    if (!fn) {17        fn = function(left, right) {18        return left[0] > right[0] ? -1 : 1;19        } 20    }21 22    let out:SortArray = {23        arr: [],24        sortIndices: []25    };26 27    let idxTracker: number[][] = []28    for (let i = 0; i < arr.length; i++) {29      idxTracker[i] = [arr[i], i];30    }31 32    idxTracker.sort(function(left, right) {33      return left[0] > right[0] ? -1 : 1;34    });35 36    for (var j = 0; j < arr.length; j++) {37      out.sortIndices.push(idxTracker[j][1]);38      out.arr[j] = idxTracker[j][0];39    }40 41    return out;42  }