-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathsorted-linked-list.js
More file actions
43 lines (31 loc) · 865 Bytes
/
sorted-linked-list.js
File metadata and controls
43 lines (31 loc) · 865 Bytes
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
class SortedLinkedList extends DoubleLinkedList {
#sortingFunction;
constructor(sortingFunction = null) {
super();
this.#sortingFunction = sortingFunction;
if(typeof sortingFunction !== 'function') {
this.#sortingFunction = (a, b) => {
if(a === b) return 0;
return a > b ? 1 : -1;
}
}
this.push = undefined;
}
insert(item) {
if(this.size === 0) {
return super.insert(item);
}
const index = this.#getNextElementIndex(item);
return super.insert(item, index);
}
#getNextElementIndex(item) {
let current = this.head;
let i = 0;
for(; i< this.size; i++) {
const res = this.#sortingFunction(item, current.value);
if(!(res >= 0) || !res) return i;
current = current.next;
}
return i;
}
}