_linearSearch.js 1.1 KB

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