This repository has been archived by the owner on Feb 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemographic_split.go
100 lines (79 loc) · 2.3 KB
/
demographic_split.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
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
package fbintegration
import (
"encoding/json"
"fmt"
"reflect"
"strconv"
facebookLib "github.com/huandu/facebook"
)
type (
// DemographicSplit comment pending
DemographicSplit struct {
Total float64
Data []DemographicSplitItem
}
// DemographicSplitItem comment pending
DemographicSplitItem struct {
Gender string `json:"gender"`
AgeRange string `json:"age_range"`
Value string `json:"value"`
}
)
// NewDemographicSplitFromResult comment pending
func NewDemographicSplitFromResult(results *facebookLib.Result, total float64) DemographicSplit {
demographicSplit := DemographicSplit{Total: total}
data := results.Get("data")
slice := reflect.ValueOf(data)
for i := 0; i < slice.Len(); i++ {
demographicSplitItem := DemographicSplitItem{
getResultValue(results, i, "gender"),
getResultValue(results, i, "age"),
getResultValue(results, i, "reach"),
}
demographicSplit.Push(demographicSplitItem)
}
return demographicSplit
}
// Push comment pending
func (d *DemographicSplit) Push(demographicSplitItem DemographicSplitItem) {
d.Data = append(d.Data, demographicSplitItem)
}
// BuildMap builds a map representation of the breakdown.
func (d DemographicSplit) BuildMap() (map[string]map[string]float64, error) {
demographicSplit := map[string]map[string]float64{}
for _, demographicSplitItem := range d.Data {
_, exists := demographicSplit[demographicSplitItem.AgeRange]
if !exists {
demographicSplit[demographicSplitItem.AgeRange] = map[string]float64{
"male": 0,
"female": 0,
}
}
value, err := strconv.ParseFloat(demographicSplitItem.Value, 64)
if err != nil {
return nil, err
}
var percentage float64
if d.Total > 0 {
percentage = (value / d.Total) * 100
}
demographicSplit[demographicSplitItem.AgeRange][demographicSplitItem.Gender] = percentage
}
return demographicSplit, nil
}
// MarshalJSON comment pending
func (d DemographicSplit) MarshalJSON() ([]byte, error) {
demographicSplitMap, err := d.BuildMap()
if err != nil {
return []byte{}, err
}
json, err := json.Marshal(demographicSplitMap)
if err != nil {
return []byte{}, err
}
return json, nil
}
func getResultValue(results *facebookLib.Result, recordIndex int, key string) string {
query := fmt.Sprintf("data.%d.%s", recordIndex, key)
return results.Get(query).(string)
}