Skip to content

Instantly share code, notes, and snippets.

@beardedtim
Last active March 28, 2017 20:16
Show Gist options
  • Select an option

  • Save beardedtim/f23ac38e536e3f707ff5b58419d4890b to your computer and use it in GitHub Desktop.

Select an option

Save beardedtim/f23ac38e536e3f707ff5b58419d4890b to your computer and use it in GitHub Desktop.
const insert = (fn = (a, b) => a < b, item, list = []) => {
if (!list.length) {
return [item];
}
if (list.length === 1) {
return fn(item, list[0]) ? [item, list[0]] : [list[0], item];
}
let min = 0;
let max = list.length - 1;
while (true) {
if (max < min) {
return list.slice(0, min).concat([item], list.slice(min));
}
const currIndex = Math.floor((min + max) / 2);
const currItem = list[currIndex];
const sort = fn(item, currItem);
if (sort) {
max = currIndex - 1;
}
if (!sort) {
min = currIndex + 1;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment