只适用于一堆连续渐变的属性的数据们进行查找,其中的某个符合特定条件的节点!

    1. class Dichotomy {
    2. constructor(arr, fn) {
    3. this.data = arr;
    4. this.rule = fn;
    5. }
    6. find() {
    7. const {data, rule} = this;
    8. const d_length = data.length;
    9. const getIndex = length => Math.round(length / 2) - 1;
    10. let index = getIndex(d_length);
    11. let min, max;
    12. while (index) {
    13. if (min && max && min + 1 === max) {
    14. this.res = max;
    15. return index = null;
    16. }
    17. const {status} = rule(index, data);
    18. console.log(status, min, max);
    19. if (status === "min") {
    20. min = min && min > index + 1 ? min : index + 1;
    21. index = getIndex(min + (max || d_length));
    22. } else if (status === "max") {
    23. max = max && max < index + 1 ? max : index + 1;
    24. index = getIndex(max);
    25. } else {
    26. this.res = status;
    27. index = null;
    28. }
    29. }
    30. console.log(this.res, "r");
    31. return this.res;
    32. }
    33. }
    34. //只适用于一堆连续渐变的属性的数据们进行查找,其中的某个符合特定条件的节点!
    35. const dichotomy = new Dichotomy(
    36. [
    37. {data: 1, priority: 300},
    38. {data: 1, priority: 200},
    39. {data: 1, priority: 100},
    40. {data: 1, priority: 50},
    41. {data: 1, priority: 25},
    42. {data: 1, priority: 12},
    43. {data: 1, priority: 6}
    44. ],
    45. (index, data) => {
    46. const obj = {data: 2, priority: 120};
    47. if (data[0].priority < obj.priority) return {
    48. status: 0
    49. };
    50. if (data[data.length - 1].priority > obj.priority)
    51. return {
    52. status: data.length - 1
    53. };
    54. const {priority} = data[index];
    55. if (priority > obj.priority) return {
    56. status: "min"
    57. };
    58. return {
    59. status: data[index - 1].priority > obj.priority ?
    60. index : "max"
    61. };
    62. }
    63. );
    64. dichotomy.find();
    65. console.log(dichotomy.res);