-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
322 lines (288 loc) · 7.71 KB
/
Copy pathmain.go
File metadata and controls
322 lines (288 loc) · 7.71 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package main
import (
"fmt"
"os"
"strconv"
"strings"
"unicode"
)
// Component is a single value with a time unit (calculator.net expression format).
type Component struct {
Value float64
Unit rune // d, h, m, s
}
// Term is one or more components separated by whitespace (e.g. "1d 2h 3m 4s").
type Term struct {
Components []Component
}
// Expression is terms separated only by + or - (spaces do not separate terms).
type Expression struct {
Terms []Term
Ops []rune // '+', '-' between Terms[i] and Terms[i+1]
}
func main() {
if len(os.Args) < 2 {
printUsage()
os.Exit(1)
}
input := strings.Join(os.Args[1:], " ")
expr, err := ParseExpression(input)
if err != nil {
fmt.Fprintf(os.Stderr, "tec: %v\n", err)
os.Exit(1)
}
sec := Evaluate(expr)
fmt.Print(FormatOutput(expr, sec))
}
func printUsage() {
fmt.Fprintf(os.Stderr, `tec — Time Expression Calculator
Usage:
tec <expression>
Expression rules (see https://www.calculator.net/time-calculator.html):
Each value is a number followed by d (days), h (hours), m (minutes), or s (seconds).
A term may combine several values with spaces, e.g. "1d 2h 3m 4s".
Terms are separated only by + or -. Example:
1d 2h 3m 4s + 4h 5s - 2030s
Examples:
tec "15m 15m"
tec 15m + 15m
tec 1d 2h 3m 4s + 4h 5s - 2030s
`)
}
// ParseExpression parses a time expression per calculator.net "expression" rules.
func ParseExpression(s string) (*Expression, error) {
s = strings.TrimSpace(s)
if s == "" {
return nil, fmt.Errorf("empty expression")
}
p := &parser{input: s}
var terms []Term
var ops []rune
first, err := p.parseTerm()
if err != nil {
return nil, err
}
terms = append(terms, first)
for {
p.skipSpace()
if p.i >= len(p.input) {
break
}
op := rune(p.input[p.i])
if op != '+' && op != '-' {
return nil, fmt.Errorf("expected '+' or '-' between terms at position %d, got %q", p.i, op)
}
p.i++
ops = append(ops, op)
next, err := p.parseTerm()
if err != nil {
return nil, err
}
if len(next.Components) == 0 {
return nil, fmt.Errorf("empty term after %q at position %d", string(op), p.i)
}
terms = append(terms, next)
}
if len(ops) != len(terms)-1 {
return nil, fmt.Errorf("internal: operator/term mismatch")
}
return &Expression{Terms: terms, Ops: ops}, nil
}
type parser struct {
input string
i int
}
func (p *parser) skipSpace() {
for p.i < len(p.input) && unicode.IsSpace(rune(p.input[p.i])) {
p.i++
}
}
func (p *parser) parseTerm() (Term, error) {
var comps []Component
for {
p.skipSpace()
if p.i >= len(p.input) {
break
}
ch := p.input[p.i]
if ch == '+' || ch == '-' {
break
}
if !unicode.IsDigit(rune(ch)) && ch != '.' {
return Term{}, fmt.Errorf("invalid character %q at position %d", ch, p.i)
}
val, err := p.parseNumber()
if err != nil {
return Term{}, err
}
p.skipSpace()
if p.i >= len(p.input) {
return Term{}, fmt.Errorf("missing unit after number at position %d", p.i)
}
u := unicode.ToLower(rune(p.input[p.i]))
if u != 'd' && u != 'h' && u != 'm' && u != 's' {
return Term{}, fmt.Errorf("invalid unit %q at position %d (want d, h, m, or s)", p.input[p.i], p.i)
}
p.i++
comps = append(comps, Component{Value: val, Unit: u})
}
if len(comps) == 0 {
return Term{}, fmt.Errorf("expected a value at position %d", p.i)
}
return Term{Components: comps}, nil
}
func (p *parser) parseNumber() (float64, error) {
start := p.i
if p.i < len(p.input) && p.input[p.i] == '.' {
return 0, fmt.Errorf("number cannot start with '.' at position %d", p.i)
}
for p.i < len(p.input) && unicode.IsDigit(rune(p.input[p.i])) {
p.i++
}
if p.i < len(p.input) && p.input[p.i] == '.' {
p.i++
for p.i < len(p.input) && unicode.IsDigit(rune(p.input[p.i])) {
p.i++
}
}
if start == p.i {
return 0, fmt.Errorf("expected number at position %d", p.i)
}
s := p.input[start:p.i]
v, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0, fmt.Errorf("invalid number %q: %w", s, err)
}
return v, nil
}
func componentToSeconds(c Component) float64 {
switch c.Unit {
case 'd':
return c.Value * 86400
case 'h':
return c.Value * 3600
case 'm':
return c.Value * 60
case 's':
return c.Value
default:
return 0
}
}
func termToSeconds(t Term) float64 {
var s float64
for _, c := range t.Components {
s += componentToSeconds(c)
}
return s
}
// Evaluate returns total seconds for the expression.
func Evaluate(e *Expression) float64 {
if len(e.Terms) == 0 {
return 0
}
total := termToSeconds(e.Terms[0])
for i := 1; i < len(e.Terms); i++ {
s := termToSeconds(e.Terms[i])
switch e.Ops[i-1] {
case '+':
total += s
case '-':
total -= s
}
}
return total
}
func formatComponent(c Component) string {
return trimFloat(c.Value) + string(c.Unit)
}
func formatTerm(t Term) string {
parts := make([]string, len(t.Components))
for i := range t.Components {
parts[i] = formatComponent(t.Components[i])
}
return strings.Join(parts, " ")
}
func trimFloat(f float64) string {
s := strconv.FormatFloat(f, 'f', -1, 64)
return s
}
// FormatOutput builds the CLI result text.
func FormatOutput(e *Expression, totalSec float64) string {
var b strings.Builder
b.WriteString("Result\n")
// Display rows: multi-term → one row per term; single term with multiple components → one row per component.
if len(e.Terms) > 1 {
b.WriteString(fmt.Sprintf("\t%s\n", formatTerm(e.Terms[0])))
for i := 1; i < len(e.Terms); i++ {
op := e.Ops[i-1]
b.WriteString(fmt.Sprintf("%c\t%s\n", op, formatTerm(e.Terms[i])))
}
} else if len(e.Terms) == 1 && len(e.Terms[0].Components) > 1 {
cs := e.Terms[0].Components
b.WriteString(fmt.Sprintf("\t%s\n", formatComponent(cs[0])))
for i := 1; i < len(cs); i++ {
b.WriteString(fmt.Sprintf("+\t%s\n", formatComponent(cs[i])))
}
} else if len(e.Terms) == 1 && len(e.Terms[0].Components) == 1 {
b.WriteString(fmt.Sprintf("\t%s\n", formatComponent(e.Terms[0].Components[0])))
}
b.WriteString(fmt.Sprintf("=\t%s\n", formatDHMS(totalSec)))
b.WriteString(fmt.Sprintf("=\t%s\n", formatUnit(totalSec, "d", 86400)))
b.WriteString(fmt.Sprintf("=\t%s\n", formatUnit(totalSec, "h", 3600)))
b.WriteString(fmt.Sprintf("=\t%s\n", formatUnit(totalSec, "m", 60)))
b.WriteString(fmt.Sprintf("=\t%s\n", formatUnit(totalSec, "s", 1)))
return b.String()
}
// formatDHMS returns a canonical d/h/m/s breakdown (e.g. 30m 0s for 1800 seconds).
func formatDHMS(totalSec float64) string {
if totalSec == 0 {
return "0s"
}
neg := totalSec < 0
t := totalSec
if neg {
t = -t
}
d := int(t / 86400)
r := t - float64(d)*86400
h := int(r / 3600)
r -= float64(h) * 3600
m := int(r / 60)
s := r - float64(m)*60
prefix := ""
if neg {
prefix = "-"
}
// Whole days only, no remainder
if h == 0 && m == 0 && s == 0 && d > 0 {
return prefix + trimFloat(float64(d)) + "d"
}
// Sub-day: seconds only (e.g. 45s)
if d == 0 && h == 0 && m == 0 {
return prefix + trimFloat(s) + "s"
}
// Sub-day: minutes + seconds (e.g. 30m 0s, 1m 30s)
if d == 0 && h == 0 {
return prefix + trimFloat(float64(m)) + "m " + trimFloat(s) + "s"
}
// Sub-day with hours: hours, minutes, seconds
if d == 0 {
return prefix + trimFloat(float64(h)) + "h " + trimFloat(float64(m)) + "m " + trimFloat(s) + "s"
}
// Days + remainder
return prefix + trimFloat(float64(d)) + "d " + trimFloat(float64(h)) + "h " + trimFloat(float64(m)) + "m " + trimFloat(s) + "s"
}
func formatUnit(totalSec float64, suffix string, div float64) string {
v := totalSec / div
return trimFloatNice(v) + " " + suffix
}
// trimFloatNice formats a float with up to 7 decimals, trimming trailing zeros (like 0.0208333 d).
func trimFloatNice(f float64) string {
s := strconv.FormatFloat(f, 'f', 7, 64)
s = strings.TrimRight(strings.TrimRight(s, "0"), ".")
if s == "" || s == "-" {
return "0"
}
return s
}