forked from charmbracelet/freeze
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cut.go
45 lines (36 loc) · 787 Bytes
/
cut.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main
import "strings"
func cut(input string, window []int) string {
if len(window) == 0 {
return input
}
if len(window) == 1 && window[0] == 0 {
return input
}
if len(window) == 2 && window[0] == 0 && window[1] == -1 {
return input
}
lines := strings.Split(input, "\n")
start := 0
end := len(lines)
switch len(window) {
case 1:
if window[0] > 0 {
start = window[0]
} else {
start = len(lines) + window[0] // add negative = subtract
}
case 2:
start = window[0]
end = window[1]
}
start = clamp(start, 0, len(lines))
end = clamp(end+1, start, len(lines))
if start == end && start < len(lines) {
return lines[start]
}
return strings.Join(lines[start:end], "\n")
}
func clamp(n, low, high int) int {
return min(max(n, low), high)
}