Add support for custom comparison function in insertion

This commit is contained in:
Sasha 2018-04-13 10:39:50 +02:00
parent d022ab9aa4
commit eb2fd7a7cb

View file

@ -1,6 +1,8 @@
function Lib(ws) {
return {
clearElement: clearElement,
defaultCompare: defaultCompare,
funMap: funMap,
insert: insert,
send: send
};
@ -11,14 +13,36 @@ function Lib(ws) {
}
}
function insert(obj, t, min, max) {
function insert(obj, t, compare, min, max) {
min = min == undefined ? 0 : min;
max = max == undefined ? t.length : max;
compare = compare == undefined ? defaultCompare : compare;
if(max - min < 1) {
return min;
}
var avg = Math.floor((max + min) / 2);
return (obj < t[avg]) ? insert(obj, t, min, avg) : insert(obj, t, avg+1, max);
if (compare(obj, t[avg]) < 0) {
return insert(obj, t, compare, min, avg);
} else {
return insert(obj, t, compare, avg+1, max);
}
}
function defaultCompare(a, b) {
if(a < b) {
return -1;
} else if(a > b) {
return 1;
} else {
return 0;
}
}
function funMap(projector, f) {
return function() {
var args = Array.prototype.map.call(arguments, projector);
return f.apply(null, args);
}
}
function send(o) {