_linearSearch.js 1.1 KB

123456789101112131415161718192021222324252627282930
  1. var _getLength = require('./_getLength.js');
  2. var isFunction = require('./isFunction.js');
  3. // Internal function for linearly iterating over arrays.
  4. function linearSearch(array, predicate, dir, start) {
  5. var target, length = _getLength(array);
  6. dir || (dir = 1);
  7. start = (
  8. start == null ? (dir > 0 ? 0 : length - 1) :
  9. start < 0 ? (dir > 0 ? Math.max(0, start + length) : start + length) :
  10. dir > 0 ? start : Math.min(start, length - 1)
  11. );
  12. // As a special case, in order to elide the `predicate` invocation on every
  13. // loop iteration, we allow the caller to pass a value that should be found by
  14. // strict equality comparison. This is somewhat like a rudimentary iteratee
  15. // shorthand. It is used in `_.indexof` and `_.lastIndexOf`.
  16. if (!isFunction(predicate)) {
  17. target = predicate && predicate.value;
  18. predicate = false;
  19. }
  20. for (; start >= 0 && start < length; start += dir) {
  21. if (
  22. predicate ? predicate(array[start], start, array) :
  23. array[start] === target
  24. ) return start;
  25. }
  26. return -1;
  27. }
  28. module.exports = linearSearch;