* Compute the longest common prefix of strings, aligned to word boundaries. * e.g. ["git fetch", "git worktree"] → "git" * ["npm run test", "npm run lint"] → "npm run"
(strings: string[])
| 180 | * ["npm run test", "npm run lint"] → "npm run" |
| 181 | */ |
| 182 | function longestCommonPrefix(strings: string[]): string { |
| 183 | if (strings.length === 0) return '' |
| 184 | if (strings.length === 1) return strings[0]! |
| 185 | |
| 186 | const first = strings[0]! |
| 187 | const words = first.split(' ') |
| 188 | let commonWords = words.length |
| 189 | |
| 190 | for (let i = 1; i < strings.length; i++) { |
| 191 | const otherWords = strings[i]!.split(' ') |
| 192 | let shared = 0 |
| 193 | while ( |
| 194 | shared < commonWords && |
| 195 | shared < otherWords.length && |
| 196 | words[shared] === otherWords[shared] |
| 197 | ) { |
| 198 | shared++ |
| 199 | } |
| 200 | commonWords = shared |
| 201 | } |
| 202 | |
| 203 | return words.slice(0, Math.max(1, commonWords)).join(' ') |
| 204 | } |
| 205 |
no test coverage detected