1 | Binary searches value in [sorted] array. [:running:] [:vhs:] [:package:] [:moon:] [:ledger:]
|
2 | > Alternatives: [bsearch], [bsearchRight], [bsearchAny], [bsearchClosest].<br>
|
3 | > This is part of package [extra-array].
|
4 |
|
5 | [extra-array]: https://www.npmjs.com/package/extra-array
|
6 |
|
7 | ```javascript
|
8 | array.bsearchAny(x, v, [fc], [fm]);
|
9 | // x: an array (sorted)
|
10 | // v: search value
|
11 | // fc: compare function (a, b)
|
12 | // fm: map function (v, i, x)
|
13 | // --> index of value | ~(index of closest value)
|
14 | ```
|
15 |
|
16 | ```javascript
|
17 | const array = require('extra-array');
|
18 |
|
19 | var x = [1, 3, 3, 3, 5];
|
20 | array.bsearchAny(x, 3);
|
21 | // 2 ^ found
|
22 |
|
23 | array.bsearchAny(x, 4);
|
24 | // -5 (~4) ^ not found, closest
|
25 |
|
26 | var x = [1, -3, -3, -3, 5];
|
27 | array.bsearchAny(x, 3, (a, b) => Math.abs(a) - Math.abs(b));
|
28 | // 2 ^
|
29 |
|
30 | array.bsearchAny(x, 3, null, v => Math.abs(v));
|
31 | // 2 ^
|
32 | ```
|
33 |
|
34 | ### references
|
35 |
|
36 | - [array-binsearch: @krisselden](https://www.npmjs.com/package/array-binsearch)
|
37 | - [binarysearch: @soldair](https://www.npmjs.com/package/binarysearch)
|
38 | - [binary-search: @darkskyapp](https://www.npmjs.com/package/binary-search)
|
39 |
|
40 | [sorted]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
|
41 | [:running:]: https://npm.runkit.com/@extra-array/bsearch-any
|
42 | [:package:]: https://www.npmjs.com/package/@extra-array/bsearch-any
|
43 | [:moon:]: https://www.npmjs.com/package/@extra-array/bsearch-any.min
|
44 | [:ledger:]: https://unpkg.com/@extra-array/bsearch-any/
|
45 | [bsearch]: https://github.com/nodef/extra-array/wiki/bsearch
|
46 | [bsearchRight]: https://github.com/nodef/extra-array/wiki/bsearchRight
|
47 | [bsearchAny]: https://github.com/nodef/extra-array/wiki/bsearchAny
|
48 | [bsearchClosest]: https://github.com/nodef/extra-array/wiki/bsearchClosest
|
49 | [:vhs:]: https://asciinema.org/a/332021
|