1
0

binary-search.js 601 B

12345678910111213141516171819202122232425262728
  1. 'use strict';
  2. var toPosInt = require('../../number/to-pos-integer')
  3. , callable = require('../../object/valid-callable')
  4. , value = require('../../object/valid-value')
  5. , floor = Math.floor;
  6. module.exports = function (compareFn) {
  7. var length, low, high, middle;
  8. value(this);
  9. callable(compareFn);
  10. length = toPosInt(this.length);
  11. low = 0;
  12. high = length - 1;
  13. while (low <= high) {
  14. middle = floor((low + high) / 2);
  15. if (compareFn(this[middle]) < 0) high = middle - 1;
  16. else low = middle + 1;
  17. }
  18. if (high < 0) return 0;
  19. if (high >= length) return length - 1;
  20. return high;
  21. };