(
stringValue: string,
matchingIndices: ReadonlyArray<{ start: number; end: number }>,
windowSize: number
)
| 21 | // |
| 22 | // If stringValue length is less than the windowSize, then we should return all the string slices of the string |
| 23 | export function getStringSlices( |
| 24 | stringValue: string, |
| 25 | matchingIndices: ReadonlyArray<{ start: number; end: number }>, |
| 26 | windowSize: number |
| 27 | ): Array<StringSlice> { |
| 28 | const slices: StringSlice[] = []; |
| 29 | |
| 30 | const addSlice = (isMatch: boolean, slice: string) => { |
| 31 | if (slice.length > 0) { |
| 32 | slices.push({ isMatch, slice }); |
| 33 | } |
| 34 | }; |
| 35 | |
| 36 | const addEllipsis = () => { |
| 37 | addSlice(false, "…"); |
| 38 | }; |
| 39 | |
| 40 | const calculateWindow = (): { start: number; end: number } => { |
| 41 | if (stringValue.length <= windowSize) { |
| 42 | return { start: 0, end: stringValue.length }; |
| 43 | } |
| 44 | |
| 45 | const largestMatch = matchingIndices.reduce( |
| 46 | (largestMatch, match) => { |
| 47 | if (match.end - match.start > largestMatch.end - largestMatch.start) { |
| 48 | return match; |
| 49 | } |
| 50 | |
| 51 | return largestMatch; |
| 52 | }, |
| 53 | { start: 0, end: 0 } |
| 54 | ); |
| 55 | |
| 56 | const largestMatchLength = largestMatch.end - largestMatch.start; |
| 57 | |
| 58 | const start = |
| 59 | largestMatch.start - Math.floor(windowSize / 2 - largestMatchLength / 2); |
| 60 | const end = |
| 61 | largestMatch.end + Math.floor(windowSize / 2 - largestMatchLength / 2); |
| 62 | |
| 63 | return { |
| 64 | start: Math.max(start, 0), |
| 65 | end: Math.min(end, stringValue.length), |
| 66 | }; |
| 67 | }; |
| 68 | |
| 69 | const window = calculateWindow(); |
| 70 | |
| 71 | let currentIndex = window.start; |
| 72 | |
| 73 | if (window.start > 0) { |
| 74 | addEllipsis(); |
| 75 | } |
| 76 | |
| 77 | for (const { start, end } of matchingIndices) { |
| 78 | if (start < window.start && end < window.start) { |
| 79 | continue; |
| 80 | } else if (start > window.end) { |
no test coverage detected