forked from aaditmshah/sorted-array
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsorted-array.js
More file actions
80 lines (67 loc) · 2.29 KB
/
sorted-array.js
File metadata and controls
80 lines (67 loc) · 2.29 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
var SortedArray = (function () {
var SortedArray = defclass({
constructor: function (array, compare, isSorted = false) {
this.compare = compare || compareDefault;
if(!isSorted) {
this.array = [];
var length = array.length;
var index = 0;
while (index < length) this.insert(array[index++]);
} else {
this.array = array;
}
},
insert: function (element) {
var array = this.array;
var compare = this.compare;
var index = array.length;
array.push(element);
while (index > 0) {
var i = index, j = --index;
if (compare(array[i], array[j]) < 0) {
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
return this;
},
search: function (element) {
var array = this.array;
var compare = this.compare;
var high = array.length;
var low = 0;
while (high > low) {
var index = (high + low) / 2 >>> 0;
var ordering = compare(array[index], element);
if (ordering < 0) low = index + 1;
else if (ordering > 0) high = index;
else return index;
}
return -1;
},
remove: function (element) {
var index = this.search(element);
if (index >= 0) this.array.splice(index, 1);
return this;
}
});
SortedArray.comparing = function (property, array) {
return new SortedArray(array, function (a, b) {
return compareDefault(property(a), property(b));
});
};
return SortedArray;
function defclass(prototype) {
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}
function compareDefault(a, b) {
if (a === b) return 0;
return a < b ? -1 : 1;
}
}());
if (typeof module === "object") module.exports = SortedArray;
if (typeof define === "function" && define.amd)
define(function () { return SortedArray; });