utils.GenerateMapOfNewData   A
last analyzed

Complexity

Conditions 5

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 18
nop 2
dl 0
loc 30
ccs 0
cts 14
cp 0
crap 30
rs 9.0333
c 0
b 0
f 0
1
package utils
2
3
import (
4
	"fmt"
5
6
	"github.com/SerhiiCho/shoshka-go/models"
7
)
8
9
// Contains function returns true if slice contains given item
10
func Contains(slice []string, needle string) bool {
11 1
	for _, sliceItem := range slice {
12 1
		if sliceItem == needle {
13 1
			return true
14
		}
15
	}
16 1
	return false
17
}
18
19
// GetUniqueItem returns unique item from a slice
20
func GetUniqueItem(slice1 []string, slice2 []string) []string {
21 1
	var result []string
22
23 1
	for _, item1 := range slice1 {
24 1
		if !Contains(slice2, item1) {
25 1
			result = append(result, item1)
26
		}
27
	}
28
29 1
	for _, item2 := range slice2 {
30 1
		if !Contains(slice1, item2) {
31 1
			result = append(result, item2)
32
		}
33
	}
34
35 1
	return result
36
}
37
38
// GetIndexOfSliceItem returns index of a slice item where value is positioned
39
func GetIndexOfSliceItem(slice []string, value string) int {
40 1
	for i, sliceItem := range slice {
41 1
		if sliceItem == value {
42 1
			return i
43
		}
44
	}
45
46
	return -1
47
}
48
49
// GenerateMapOfNewData returns nil if there are no new photo reports
50
func GenerateMapOfNewData(titles []string, photoReports []models.PhotoReport) []models.PhotoReport {
51
	oldTitles := GetCached("titles")
52
	newPhotoReportTitles := GetUniqueItem(titles, oldTitles)
53
54
	if len(titles) > 0 {
55
		PutIntoCache(titles, "titles")
56
	}
57
58
	if len(newPhotoReportTitles) == 0 {
59
		fmt.Println("There are no new photo reports")
60
		return nil
61
	}
62
63
	var tgMessageData []models.PhotoReport
64
65
	for _, newReportTitle := range newPhotoReportTitles {
66
		index := GetIndexOfSliceItem(titles, newReportTitle)
67
68
		if index == -1 {
69
			continue
70
		}
71
72
		tgMessageData = append(tgMessageData, models.PhotoReport{
73
			Title: newReportTitle,
74
			Image: photoReports[index].Image,
75
			URL:   photoReports[index].URL,
76
		})
77
	}
78
79
	return tgMessageData
80
}
81
82
// GetTitlesFromPhotoReports returns only titles from slice of messsage data
83
func GetTitlesFromPhotoReports(photoReports []models.PhotoReport) []string {
84
	var titles []string
85
86
	for _, photoReport := range photoReports {
87
		titles = append(titles, photoReport.Title)
88
	}
89
90
	return titles
91
}
92