Skip to content

Instantly share code, notes, and snippets.

@rkatic
Last active December 15, 2015 13:39
Show Gist options
  • Save rkatic/5269339 to your computer and use it in GitHub Desktop.
Save rkatic/5269339 to your computer and use it in GitHub Desktop.
// array already sorted!
function unique( array ) {
var j = 0,
i = 1,
l = array.length | 0;
while ( i < l && array[i-1] !== array[i] ) {
++i;
}
if ( i < l ) {
for ( j = i++; i < l; ++i ) {
if ( array[i-1] !== array[i] ) {
array[j++] = array[i];
}
}
array.length = j; // array.splice( j, l-j ); to support jQuery objects
}
return array;
}
function uniqueMerge( array, B, cmp ) {
var A, x = 0,
i = 0, j = 0,
ii = array.length|0,
jj = B.length|0;
if ( ii === 0 || jj === 0 || cmp(array[ii-1], B[0]) < 0 ) {
for ( ; j < jj; ++j ) {
array.push( B[j] );
}
return array;
}
var x = getInsertionPosition( array, B[0], cmp );
A = array.slice(x);
ii = A.length;
while ( i < ii && j < jj ) {
d = cmp( A[i], B[j] );
if ( d < 0 ) {
array[x++] = A[i++];
} else {
array[x++] = B[j++];
if ( d === 0 ) {
++i;
}
}
}
while ( i < ii ) array[x++] = A[i++];
while ( j < jj ) array[x++] = B[j++];
array.length = x;
return array;
}
// array is sorted and with no duplicates
function getInsertionPosition( array, val, cmp ) {
var lo = 0, hi = array.length|0, mid = 0;
while ( lo < hi ) {
mid = lo + hi >>> 1;
if ( cmp( array[mid], val ) < 0 ) {
lo = mid + 1;
} else {
hi = mid;
}
}
return hi;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment