You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

findRangesImmutable.js 945 B

3 years ago
12345678910111213141516171819202122232425262728293031323334353637383940
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @format
  8. *
  9. * @emails oncall+draft_js
  10. */
  11. 'use strict';
  12. /**
  13. * Search through an array to find contiguous stretches of elements that
  14. * match a specified filter function.
  15. *
  16. * When ranges are found, execute a specified `found` function to supply
  17. * the values to the caller.
  18. */
  19. function findRangesImmutable(haystack, areEqualFn, filterFn, foundFn) {
  20. if (!haystack.size) {
  21. return;
  22. }
  23. var cursor = 0;
  24. haystack.reduce(function (value, nextValue, nextIndex) {
  25. if (!areEqualFn(value, nextValue)) {
  26. if (filterFn(value)) {
  27. foundFn(cursor, nextIndex);
  28. }
  29. cursor = nextIndex;
  30. }
  31. return nextValue;
  32. });
  33. filterFn(haystack.last()) && foundFn(cursor, haystack.count());
  34. }
  35. module.exports = findRangesImmutable;