mirror of
https://github.com/jimeh/undent.git
synced 2026-02-19 11:56:39 +00:00
perf: simplify line-feed and minimum indentation loops
This is based on performance improvements suggested by OpenAI's ChatGPT.
This commit is contained in:
52
undent.go
52
undent.go
@@ -5,6 +5,7 @@ package undent
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -20,50 +21,33 @@ func Bytes(s string) []byte {
|
||||
return []byte{}
|
||||
}
|
||||
|
||||
// find line feeds
|
||||
lfs := []int{}
|
||||
|
||||
if s[0] != lf {
|
||||
lfs = append(lfs, -1)
|
||||
}
|
||||
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == lf {
|
||||
lfs = append(lfs, i)
|
||||
}
|
||||
}
|
||||
|
||||
// find smallest indent relative to each line-feed
|
||||
min := 99999999999
|
||||
count := 0
|
||||
|
||||
for i := 0; i < len(lfs); i++ {
|
||||
offset := lfs[i]
|
||||
end := len(s) - 1
|
||||
if i+1 < len(lfs) {
|
||||
end = lfs[i+1]
|
||||
}
|
||||
lfs := make([]int, 0, strings.Count(s, "\n"))
|
||||
if s[0] != lf {
|
||||
lfs = append(lfs, -1)
|
||||
}
|
||||
|
||||
if offset+1 >= end {
|
||||
continue
|
||||
}
|
||||
|
||||
indent := 0
|
||||
lineSeek:
|
||||
for n := offset + 1; n < end && indent < min; n++ {
|
||||
switch s[n] {
|
||||
indent := 0
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == lf {
|
||||
lfs = append(lfs, i)
|
||||
indent = 0
|
||||
} else if indent < min {
|
||||
switch s[i] {
|
||||
case spc, tab:
|
||||
indent++
|
||||
default:
|
||||
break lineSeek
|
||||
if indent > 0 {
|
||||
count++
|
||||
}
|
||||
if indent < min {
|
||||
min = indent
|
||||
}
|
||||
}
|
||||
}
|
||||
if indent < min {
|
||||
min = indent
|
||||
}
|
||||
if indent > 0 {
|
||||
count++
|
||||
}
|
||||
}
|
||||
|
||||
// extract each line without indentation
|
||||
|
||||
Reference in New Issue
Block a user