Skip to content

Commit

Permalink
feat(arrays): add argSort()
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Mar 9, 2022
1 parent f8284ce commit 4b65c36
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
33 changes: 33 additions & 0 deletions packages/arrays/src/arg-sort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { compare } from "@thi.ng/compare/compare";
import { fillRange } from "./fill-range.js";
import { sortByCachedKey } from "./sort-cached.js";

/**
* Returns a new array of numeric indices in same order as sorted values of
* `src` using given (optional) comparator (default: thi.ng/compare). The `src`
* array will remain unmodified.
*
* @remarks
* Also see {@link swizzle} to read an array in custom order.
*
* @example
* ```ts
* const src = ["a", "c", "d", "b"];
*
* argSort(src)
* // [ 0, 3, 1, 2 ]
*
* // src[0] => "a"
* // src[3] => "b"
* // src[1] => "c"
* // src[2] => "d"
*
* swizzle(argSort(src))(src)
* // [ 'a', 'b', 'c', 'd' ]
* ```
*
* @param src -
* @param cmp -
*/
export const argSort = <T>(src: T[], cmp = compare) =>
sortByCachedKey(fillRange(new Array(src.length)), src.slice(), cmp);
1 change: 1 addition & 0 deletions packages/arrays/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from "./api.js";
export * from "./arg-sort.js";
export * from "./binary-search.js";
export * from "./bisect.js";
export * from "./ends-with.js";
Expand Down

0 comments on commit 4b65c36

Please sign in to comment.