-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathis-sorted.ts
57 lines (43 loc) · 1.07 KB
/
is-sorted.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import type { PrototypeStruct } from '../index.js';
export function isArraySorted<T>(list: T[]): boolean {
const len = list.length;
if (!len || 1 === len) return true;
let sorted = true;
let prev = 0;
for (const n of list) {
const nType = typeof(n);
if ('string' === nType && 1 === (n as unknown as string).length) {
const pt = (n as unknown as string).codePointAt(0)!;
if (pt < prev) {
sorted = false;
break;
}
prev = pt;
continue;
} else if ('number' === nType) {
if (n as unknown as number < prev) {
sorted = false;
break;
}
prev = n as unknown as number;
continue;
}
sorted = false;
break;
}
return sorted;
}
interface IsSorted {
isSorted(): boolean;
}
export const isSorted: PrototypeStruct = {
label: 'isSorted',
fn: function arrayIsSorted<T>(): boolean {
const ctx = this as unknown as T[];
return isArraySorted(ctx);
},
};
declare global {
// tslint:disable-next-line: no-empty-interface
interface Array<T> extends IsSorted {}
}