๐Ÿš€ Grammar-Aware Code Formatter: Structure through separation (supports Go, JavaScript, TypeScript, JSX, and TSX)
go formatter code-formatter javascript typescript jsx tsx
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

perf(formatter): Optimise regular expressions and string operations

Fuwn edc1037b b6f8267e

+26 -13
+26 -13
formatter.go
··· 14 14 closingBracePattern = regexp.MustCompile(`^\s*[\}\)]`) 15 15 openingBracePattern = regexp.MustCompile(`[\{\(]\s*$`) 16 16 caseLabelPattern = regexp.MustCompile(`^\s*(case\s+.*|default\s*):\s*$`) 17 - commentOnlyPattern = regexp.MustCompile(`^\s*//`) 18 - packageLinePattern = regexp.MustCompile(`^package\s+`) 19 17 ) 18 + 19 + func isCommentOnly(line string) bool { 20 + for index := range len(line) { 21 + character := line[index] 22 + 23 + if character == ' ' || character == '\t' { 24 + continue 25 + } 26 + 27 + return len(line) > index+1 && line[index] == '/' && line[index+1] == '/' 28 + } 29 + 30 + return false 31 + } 32 + 33 + func isPackageLine(trimmed string) bool { 34 + return len(trimmed) > 8 && trimmed[:8] == "package " 35 + } 20 36 21 37 type CommentMode int 22 38 ··· 181 197 182 198 func (f *Formatter) rewrite(source []byte, lineInfoMap map[int]*lineInfo) []byte { 183 199 lines := strings.Split(string(source), "\n") 184 - 185 - var result []string 186 - 200 + result := make([]string, 0, len(lines)) 187 201 previousWasOpenBrace := false 188 202 previousType := "" 189 203 previousWasComment := false ··· 205 219 206 220 lineNumber := index + 1 207 221 trimmed := strings.TrimSpace(line) 208 - isBlank := trimmed == "" 209 - isClosingBrace := closingBracePattern.MatchString(line) 210 - isOpeningBrace := openingBracePattern.MatchString(line) 211 - isCaseLabel := caseLabelPattern.MatchString(line) 212 - isCommentOnlyLine := commentOnlyPattern.MatchString(line) 213 - isPackageLine := packageLinePattern.MatchString(trimmed) 214 222 215 - if isBlank { 223 + if trimmed == "" { 216 224 continue 217 225 } 218 226 227 + isClosingBrace := closingBracePattern.MatchString(line) 228 + isOpeningBrace := openingBracePattern.MatchString(line) 229 + isCaseLabel := caseLabelPattern.MatchString(line) 230 + isCommentOnlyLine := isCommentOnly(line) 231 + isPackageLine := isPackageLine(trimmed) 219 232 info := lineInfoMap[lineNumber] 220 233 currentType := "" 221 234 ··· 305 318 continue 306 319 } 307 320 308 - if commentOnlyPattern.MatchString(lines[index]) { 321 + if isCommentOnly(lines[index]) { 309 322 continue 310 323 } 311 324