• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

handshake-org / hsd / 5770839166

pending completion
5770839166

push

github

nodech
pkg: update latest version.

7478 of 12752 branches covered (58.64%)

Branch coverage included in aggregate %.

23903 of 32971 relevant lines covered (72.5%)

31615.85 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

60.34
/lib/utils/binary.js
1
/*!
2
 * binary.js - binary search utils for hsd
3
 * Copyright (c) 2017-2018, Christopher Jeffrey (MIT License).
4
 * https://github.com/handshake-org/hsd
5
 */
6

7
'use strict';
8

9
/**
10
 * Perform a binary search on a sorted array.
11
 * @param {Array} items
12
 * @param {Object} key
13
 * @param {Function} compare
14
 * @param {Boolean?} insert
15
 * @returns {Number} Index.
16
 */
17

18
exports.search = function search(items, key, compare, insert) {
68✔
19
  let start = 0;
16,443✔
20
  let end = items.length - 1;
16,443✔
21

22
  while (start <= end) {
16,443✔
23
    const pos = (start + end) >>> 1;
79,125✔
24
    const cmp = compare(items[pos], key);
79,125✔
25

26
    if (cmp === 0)
79,125✔
27
      return pos;
133✔
28

29
    if (cmp < 0)
78,992✔
30
      start = pos + 1;
78,683✔
31
    else
32
      end = pos - 1;
309✔
33
  }
34

35
  if (!insert)
16,310!
36
    return -1;
×
37

38
  return start;
16,310✔
39
};
40

41
/**
42
 * Perform a binary insert on a sorted array.
43
 * @param {Array} items
44
 * @param {Object} item
45
 * @param {Function} compare
46
 * @returns {Number} index
47
 */
48

49
exports.insert = function insert(items, item, compare, uniq) {
68✔
50
  const i = exports.search(items, item, compare, true);
392✔
51

52
  if (uniq && i < items.length) {
392!
53
    if (compare(items[i], item) === 0)
×
54
      return -1;
×
55
  }
56

57
  if (i === 0)
392✔
58
    items.unshift(item);
346✔
59
  else if (i === items.length)
46✔
60
    items.push(item);
40✔
61
  else
62
    items.splice(i, 0, item);
6✔
63

64
  return i;
392✔
65
};
66

67
/**
68
 * Perform a binary removal on a sorted array.
69
 * @param {Array} items
70
 * @param {Object} item
71
 * @param {Function} compare
72
 * @returns {Boolean}
73
 */
74

75
exports.remove = function remove(items, item, compare) {
68✔
76
  const i = exports.search(items, item, compare, false);
×
77

78
  if (i === -1)
×
79
    return false;
×
80

81
  splice(items, i);
×
82

83
  return true;
×
84
};
85

86
/*
87
 * Helpers
88
 */
89

90
function splice(list, i) {
91
  if (i === 0) {
×
92
    list.shift();
×
93
    return;
×
94
  }
95

96
  let k = i + 1;
×
97

98
  while (k < list.length)
×
99
    list[i++] = list[k++];
×
100

101
  list.pop();
×
102
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc