summaryrefslogtreecommitdiff
path: root/internal/calculator/calculator.go
blob: fdca99b322f863711808bee661043d4d0b3e6fbb (plain)
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
package calculator

import (
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

func Parse(input string) (string, error) {
	input = strings.ToLower(strings.TrimSpace(input))
	input = strings.ReplaceAll(input, "what is ", "")
	input = strings.TrimSpace(input)

	if result, ok := parseXPercentOfY(input); ok {
		return result, nil
	}

	if result, ok := parseXIsWhatPercentOfY(input); ok {
		return result, nil
	}

	if result, ok := parseXIsYPercentOfWhat(input); ok {
		return result, nil
	}

	return "", fmt.Errorf("unable to parse input. See usage for examples")
}

func parseXPercentOfY(input string) (string, bool) {
	re := regexp.MustCompile(`^(\d+(?:\.\d+)?)\s*%\s*(?:of\s+)?(\d+(?:\.\d+)?)$`)
	matches := re.FindStringSubmatch(input)

	if matches == nil {
		return "", false
	}

	percent, _ := strconv.ParseFloat(matches[1], 64)
	base, _ := strconv.ParseFloat(matches[2], 64)

	result := (percent / 100.0) * base

	output := fmt.Sprintf("%.2f%% of %.2f = %.2f\n", percent, base, result)
	output += fmt.Sprintf("  Steps: (%.2f / 100) * %.2f = %.2f * %.2f = %.2f", percent, base, percent/100.0, base, result)

	return output, true
}

func parseXIsWhatPercentOfY(input string) (string, bool) {
	re := regexp.MustCompile(`^(\d+(?:\.\d+)?)\s+is\s+what\s*%\s*(?:of\s+)?(\d+(?:\.\d+)?)$`)
	matches := re.FindStringSubmatch(input)

	if matches == nil {
		return "", false
	}

	part, _ := strconv.ParseFloat(matches[1], 64)
	whole, _ := strconv.ParseFloat(matches[2], 64)

	if whole == 0 {
		return "", false
	}

	percent := (part / whole) * 100.0

	output := fmt.Sprintf("%.2f is %.2f%% of %.2f\n", part, percent, whole)
	output += fmt.Sprintf("  Steps: (%.2f / %.2f) * 100 = %.2f * 100 = %.2f%%", part, whole, part/whole, percent)

	return output, true
}

func parseXIsYPercentOfWhat(input string) (string, bool) {
	re := regexp.MustCompile(`^(\d+(?:\.\d+)?)\s+is\s+(\d+(?:\.\d+)?)\s*%\s*(?:of\s+)?what$`)
	matches := re.FindStringSubmatch(input)

	if matches == nil {
		return "", false
	}

	part, _ := strconv.ParseFloat(matches[1], 64)
	percent, _ := strconv.ParseFloat(matches[2], 64)

	if percent == 0 {
		return "", false
	}

	whole := (part / percent) * 100.0

	output := fmt.Sprintf("%.2f is %.2f%% of %.2f\n", part, percent, whole)
	output += fmt.Sprintf("  Steps: (%.2f / %.2f) * 100 = %.2f * 100 = %.2f", part, percent, part/percent, whole)

	return output, true
}