1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | "use strict";
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | const compileSearch = (funcName, predicate, reversed, extraArgs, earlyOut) => {
|
12 | const code = [
|
13 | "function ",
|
14 | funcName,
|
15 | "(a,l,h,",
|
16 | extraArgs.join(","),
|
17 | "){",
|
18 | earlyOut ? "" : "var i=",
|
19 | reversed ? "l-1" : "h+1",
|
20 | ";while(l<=h){var m=(l+h)>>>1,x=a[m]"
|
21 | ];
|
22 |
|
23 | if (earlyOut) {
|
24 | if (predicate.indexOf("c") < 0) {
|
25 | code.push(";if(x===y){return m}else if(x<=y){");
|
26 | } else {
|
27 | code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){");
|
28 | }
|
29 | } else {
|
30 | code.push(";if(", predicate, "){i=m;");
|
31 | }
|
32 | if (reversed) {
|
33 | code.push("l=m+1}else{h=m-1}");
|
34 | } else {
|
35 | code.push("h=m-1}else{l=m+1}");
|
36 | }
|
37 | code.push("}");
|
38 | if (earlyOut) {
|
39 | code.push("return -1};");
|
40 | } else {
|
41 | code.push("return i};");
|
42 | }
|
43 | return code.join("");
|
44 | };
|
45 |
|
46 | const compileBoundsSearch = (predicate, reversed, suffix, earlyOut) => {
|
47 | const arg1 = compileSearch(
|
48 | "A",
|
49 | "x" + predicate + "y",
|
50 | reversed,
|
51 | ["y"],
|
52 | earlyOut
|
53 | );
|
54 |
|
55 | const arg2 = compileSearch(
|
56 | "P",
|
57 | "c(x,y)" + predicate + "0",
|
58 | reversed,
|
59 | ["y", "c"],
|
60 | earlyOut
|
61 | );
|
62 |
|
63 | const fnHeader = "function dispatchBinarySearch";
|
64 |
|
65 | const fnBody =
|
66 | "(a,y,c,l,h){\
|
67 | if(typeof(c)==='function'){\
|
68 | return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\
|
69 | }else{\
|
70 | return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\
|
71 | }}\
|
72 | return dispatchBinarySearch";
|
73 |
|
74 | const fnArgList = [arg1, arg2, fnHeader, suffix, fnBody, suffix];
|
75 | const fnSource = fnArgList.join("");
|
76 | const result = new Function(fnSource);
|
77 | return result();
|
78 | };
|
79 |
|
80 | module.exports = {
|
81 | ge: compileBoundsSearch(">=", false, "GE"),
|
82 | gt: compileBoundsSearch(">", false, "GT"),
|
83 | lt: compileBoundsSearch("<", true, "LT"),
|
84 | le: compileBoundsSearch("<=", true, "LE"),
|
85 | eq: compileBoundsSearch("-", true, "EQ", true)
|
86 | };
|