Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5630055
commit 65b29f4
Showing
3 changed files
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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; | ||
}; |