Skip to content

Instantly share code, notes, and snippets.

@surr-name
Last active April 15, 2017 18:08
Show Gist options
  • Save surr-name/c90757b3532f4829f460ff95e345b13d to your computer and use it in GitHub Desktop.
Save surr-name/c90757b3532f4829f460ff95e345b13d to your computer and use it in GitHub Desktop.
const findSubsetBorders = (function(){
function findSubsetBorders ( set, str ) {
const
max = set.length - 1,
strl = str.length,
low = findLowBorder( set, 0, max, str, strl);
return {
start : low,
end : findHighBorder(set, low, max, str, strl)
}
}
function findLowBorder ( set, min, max, str, strl ) {
var m;
while ( m = bisect(min, max) ) {
if ( compare(set[m], str, strl, false) >= 0 ) max = m;
else min = m;
}
return compare(set[min], str, strl, true) === 0
? min
: max;
}
function findHighBorder ( set, min, max, str, strl ) {
var m;
while ( m = bisect(min, max) ) {
if ( compare(set[m], str, strl, true) <= 0 ) min = m;
else max = m;
}
return compare(set[max], str, strl, true) === 0
? max
: min;
}
function bisect ( min, max ) {
var diff = max - min;
return diff < 2 ? 0 : min + ( diff>>1 )
}
function compare ( a, b, bl, doSubstr ) {
if ( doSubstr ) a = a.substring(0, bl);
return a < b
? -1
: a > b
? 1
: 0;
}
return findSubsetBorders;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment