Passed
Push — master ( d1f21b...03180d )
by Serhii
02:29 queued 01:02
created

timeago.go   A

Size/Duplication

Total Lines 157
Duplicated Lines 0 %

Test Coverage

Coverage 92.86%

Importance

Changes 0
Metric Value
cc 33
eloc 95
dl 0
loc 157
ccs 52
cts 56
cp 0.9286
crap 33.3962
rs 9.76
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
C timeago.getWords 0 16 9
A timeago.getLastNumber 0 5 1
A timeago.trans 0 22 4
A timeago.getOption 0 10 2
A timeago.getTimeCalculations 0 9 1
C timeago.calculateTheResult 0 25 11
A timeago.Take 0 15 4
A timeago.getTimeTranslations 0 9 1
1
package timeago
2
3
import (
4
	"fmt"
5
	"log"
6
	"math"
7
	"path"
8
	"runtime"
9
	"strconv"
10
	"strings"
11
	"time"
12
13
	"github.com/SerhiiCho/timeago/models"
14
	"github.com/SerhiiCho/timeago/utils"
15
)
16
17
// Take coverts given datetime into `x time ago` format.
18
// For displaying `Online` word if date interval within
19
// 60 seconds, add `|online` flag to the datetime string.
20
// Format must be [year-month-day hours:minutes:seconds}
21
func Take(datetime string) string {
22 1
	option, hasOption := getOption(&datetime)
23
24 1
	loc, _ := time.LoadLocation(location)
25 1
	parsedTime, _ := time.ParseInLocation("2006-01-02 15:04:05", datetime, loc)
26 1
	seconds := int(time.Now().In(loc).Sub(parsedTime).Seconds())
27
28 1
	switch {
29
	case seconds < 0 && option == "online":
30 1
		return trans().Online
31
	case seconds < 0:
32 1
		return getWords("seconds", 0)
33
	}
34
35 1
	return calculateTheResult(seconds, hasOption, option)
36
}
37
38
func calculateTheResult(seconds int, hasOption bool, option string) string {
39 1
	minutes, hours, days, weeks, months, years := getTimeCalculations(float64(seconds))
40
41 1
	switch {
42
	case hasOption && option == "online" && seconds < 60:
43 1
		return trans().Online
44
	case seconds < 60:
45 1
		return getWords("seconds", seconds)
46
	case minutes < 60:
47 1
		return getWords("minutes", minutes)
48
	case hours < 24:
49 1
		return getWords("hours", hours)
50
	case days < 7:
51 1
		return getWords("days", days)
52
	case weeks < 4:
53 1
		return getWords("weeks", weeks)
54
	case months < 12:
55 1
		if months == 0 {
56
			months = 1
57
		}
58
59 1
		return getWords("months", months)
60
	}
61
62 1
	return getWords("years", years)
63
}
64
65
func getTimeCalculations(seconds float64) (int, int, int, int, int, int) {
66 1
	minutes := math.Round(seconds / 60)
67 1
	hours := math.Round(seconds / 3600)
68 1
	days := math.Round(seconds / 86400)
69 1
	weeks := math.Round(seconds / 604800)
70 1
	months := math.Round(seconds / 2629440)
71 1
	years := math.Round(seconds / 31553280)
72
73 1
	return int(minutes), int(hours), int(days), int(weeks), int(months), int(years)
74
}
75
76
// get the last number of a given integer
77
func getLastNumber(num int) int {
78 1
	numStr := strconv.Itoa(num)
79 1
	result, _ := strconv.Atoi(numStr[len(numStr)-1:])
80
81 1
	return result
82
}
83
84
// getWords decides rather the word must be singular or plural,
85
// and depending on the result it adds the correct word after
86
// the time number
87
func getWords(timeKind string, num int) string {
88 1
	lastNum := getLastNumber(num)
89 1
	index := 2
90
91 1
	switch {
92
	case lastNum == 1 && num == 11:
93 1
		index = 2
94
	case lastNum == 1 && language == "ru" || num == 1 && language == "en":
95 1
		index = 0
96
	case lastNum > 1 && lastNum < 5:
97 1
		index = 1
98
	}
99
100 1
	timeTrans := getTimeTranslations()
101
102 1
	return strconv.Itoa(num) + " " + timeTrans[timeKind][index] + " " + trans().Ago
103
}
104
105
// getTimeTranslations returns array of translations for different
106
// cases. For example `1 second` must not have `s` at the end
107
// but `2 seconds` requires `s`. So this method keeps all
108
// possible options for the translated word.
109
func getTimeTranslations() map[string][]string {
110 1
	return map[string][]string{
111
		"seconds": {trans().Second, trans().Seconds, trans().Seconds2},
112
		"minutes": {trans().Minute, trans().Minutes, trans().Minutes2},
113
		"hours":   {trans().Hour, trans().Hours, trans().Hours2},
114
		"days":    {trans().Day, trans().Days, trans().Days2},
115
		"weeks":   {trans().Week, trans().Weeks, trans().Weeks2},
116
		"months":  {trans().Month, trans().Months, trans().Months2},
117
		"years":   {trans().Year, trans().Years, trans().Years2},
118
	}
119
}
120
121
// getOption check if datetime has option with time,
122
// if yes, it will return this option and remove it
123
// from datetime
124
func getOption(datetime *string) (string, bool) {
125 1
	date := *datetime
126 1
	spittedDateString := strings.Split(date, "|")
127
128 1
	if len(spittedDateString) > 1 {
129 1
		*datetime = spittedDateString[0]
130 1
		return spittedDateString[1], true
131
	}
132
133 1
	return "", false
134
}
135
136
func trans() models.Lang {
137 1
	_, filename, _, ok := runtime.Caller(0)
138
139 1
	if !ok {
140
		panic("No caller information")
141
	}
142
143 1
	rootPath := path.Dir(filename)
144
145 1
	filePath := fmt.Sprintf(rootPath+"/langs/%s.json", language)
146
147 1
	thereIsFile, err := utils.FileExists(filePath)
148
149 1
	if !thereIsFile {
150
		log.Fatalf("File with the path: %s, doesn't exist", filePath)
151
	}
152
153 1
	if err != nil {
154
		log.Fatalf("Error while trying to read file %s. Error: %v", filePath, err)
155
	}
156
157 1
	return parseNeededFile(filePath)
158
}
159