index.js 823 B

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * Get the count of the longest repeating streak of `substring` in `value`.
  3. *
  4. * @param {string} value
  5. * Content to search in.
  6. * @param {string} substring
  7. * Substring to look for, typically one character.
  8. * @returns {number}
  9. * Count of most frequent adjacent `substring`s in `value`.
  10. */
  11. export function longestStreak(value, substring) {
  12. const source = String(value)
  13. let index = source.indexOf(substring)
  14. let expected = index
  15. let count = 0
  16. let max = 0
  17. if (typeof substring !== 'string') {
  18. throw new TypeError('Expected substring')
  19. }
  20. while (index !== -1) {
  21. if (index === expected) {
  22. if (++count > max) {
  23. max = count
  24. }
  25. } else {
  26. count = 1
  27. }
  28. expected = index + substring.length
  29. index = source.indexOf(substring, expected)
  30. }
  31. return max
  32. }