Last active
March 28, 2017 20:16
-
-
Save beardedtim/f23ac38e536e3f707ff5b58419d4890b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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