Skip to content
This repository has been archived by the owner on Mar 30, 2020. It is now read-only.

Commit

Permalink
pack and unpack list of periods
Browse files Browse the repository at this point in the history
  • Loading branch information
mcuadros committed May 13, 2015
1 parent f89b8b1 commit 2916c87
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 18 deletions.
6 changes: 3 additions & 3 deletions aggregator.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"time"
)

type Period int64
type Period uint64

type TimeAggregator struct {
Values map[Period]*Aggregator
Expand All @@ -22,7 +22,7 @@ func NewTimeAggregator(p ...PeriodDefinition) *TimeAggregator {
}

func (a *TimeAggregator) Add(date time.Time, value int64) {
p := a.periods.calc(date)
p := a.periods.pack(date)

if _, ok := a.Values[p]; !ok {
a.Values[p] = a.buildAggregator()
Expand All @@ -32,7 +32,7 @@ func (a *TimeAggregator) Add(date time.Time, value int64) {
}

func (a *TimeAggregator) Get(date time.Time) int64 {
p := a.periods.calc(date)
p := a.periods.pack(date)

if _, ok := a.Values[p]; !ok {
return -1
Expand Down
32 changes: 17 additions & 15 deletions periods.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (

type PeriodDefinition struct {
size int8
pad int64
pad uint64
name string
cast func(date time.Time) Period
}
Expand Down Expand Up @@ -49,25 +49,27 @@ var Weekday = PeriodDefinition{

type periodDefinitions []PeriodDefinition

func (p periodDefinitions) calc(date time.Time) Period {
var t Period
func (p periodDefinitions) pack(date time.Time) Period {
t := Period(1)
for _, p := range p[:len(p)-1] {
t += (p.cast(date) * Period(p.pad))
t *= Period(p.pad)
t += p.cast(date)
}

return t
}

/*
func (p periodDefinitions) extract(date time.Time) map[string]int64 {
result := make(map[string]int64, 0)
for _, p := range p[:len(p)-1] {
result[p.name] =
}
func (p periodDefinitions) unpack(total Period) map[string]uint64 {
result := make(map[string]uint64, 0)
t := uint64(total)
for i := len(p) - 2; i >= 0; i-- {
result[p[i].name] = t % p[i].pad
t = t / p[i].pad
}

fmt.Println("period", t)
if t != 1 {
panic("Malformed period")
}

return t
}*/
return result
}
16 changes: 16 additions & 0 deletions periods_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package ta

import (
. "gopkg.in/check.v1"
)

func (s *UtilsSuite) TestperiodDefinitions_pack(c *C) {
ps := periodDefinitions{Year, Month, Weekday}
c.Assert(ps.pack(date2015November), Equals, Period(1201511))
}

func (s *UtilsSuite) TestperiodDefinitions_unpack(c *C) {
ps := periodDefinitions{Year, Month, Weekday}
p := ps.unpack(Period(1201511))
c.Assert(p, DeepEquals, map[string]uint64{"year": 2015, "month": 11})
}

0 comments on commit 2916c87

Please sign in to comment.