Skip to content

Commit

Permalink
feat(arrays): add isSorted()
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Oct 26, 2019
1 parent 5630055 commit 65b29f4
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/arrays/README.md
Expand Up @@ -51,6 +51,7 @@ import * as a from "@thi.ng/arrays";
- [ensureArray()](https://github.com/thi-ng/umbrella/tree/master/packages/arrays/src/ensure-array.ts)
- [ensureIterable()](https://github.com/thi-ng/umbrella/tree/master/packages/arrays/src/ensure-iterable.ts)
- [fuzzyMatch()](https://github.com/thi-ng/umbrella/tree/master/packages/arrays/src/fuzzy-match.ts)
- [isSorted()](https://github.com/thi-ng/umbrella/tree/master/packages/arrays/src/is-sorted.ts)
- [multiSwap()](https://github.com/thi-ng/umbrella/tree/master/packages/arrays/src/swap.ts)
- [peek()](https://github.com/thi-ng/umbrella/tree/master/packages/arrays/src/peek.ts)
- [quickSort()](https://github.com/thi-ng/umbrella/tree/master/packages/arrays/src/quicksort.ts)
Expand Down
1 change: 1 addition & 0 deletions packages/arrays/src/index.ts
Expand Up @@ -4,6 +4,7 @@ export * from "./ensure-array";
export * from "./ensure-iterable";
export * from "./find";
export * from "./fuzzy-match";
export * from "./is-sorted";
export * from "./peek";
export * from "./quicksort";
export * from "./shuffle";
Expand Down
38 changes: 38 additions & 0 deletions packages/arrays/src/is-sorted.ts
@@ -0,0 +1,38 @@
import { Comparator } from "@thi.ng/api";
import { compare } from "@thi.ng/compare";

/**
* Returns true if the given array and its elements in the selected
* index range (entire array, by default) are in the order defined by
* the given comparator (thi.ng/compare by default). Always returns
* true, if effective index range (or array length) has less than two
* elements. No bounds checking.
*
* ```
* isSorted([3, 2, 1])
* // false
*
* // w/ custom comparator
* isSorted([3, 2, 1], (a, b) => b - a)
* // true
* ```
*
* @param arr
* @param cmp
* @param start
* @param end
*/
export const isSorted = <T>(
arr: ArrayLike<T>,
cmp: Comparator<T> = compare,
start = 0,
end = arr.length
) => {
let prev = arr[start];
while (++start < end) {
const curr = arr[start];
if (cmp(prev, curr) > 0) return false;
prev = curr;
}
return true;
};

0 comments on commit 65b29f4

Please sign in to comment.