Add methods for Bucket structs

master
Buddy Sandidge 5 years ago
parent af8e7ebedb
commit 0943ed42dd

@ -7,3 +7,25 @@ type Bucket struct {
// Volume is the current volume of the bucket
Volume uint64
}
// Fill sets the volume to the capacity to fill bucket
func (b *Bucket) Fill() {
b.Volume = b.Capacity
}
// Empty sets the volume to 0
func (b *Bucket) Empty() {
b.Volume = 0
}
// Pour fills the target bucket to the top
func (b *Bucket) Pour(target *Bucket) {
availableVolume := target.Capacity - target.Volume
if availableVolume > b.Volume {
target.Volume += b.Volume
b.Volume = 0
} else {
b.Volume -= availableVolume
target.Volume += availableVolume
}
}

@ -0,0 +1,28 @@
package bucket
import "testing"
func TestPour(t *testing.T) {
var testcases = []struct {
source *Bucket
target *Bucket
expectedSrcVol uint64
expectedTargetVol uint64
}{
{&Bucket{Capacity: 5, Volume: 2}, &Bucket{Capacity: 3, Volume: 2}, 1, 3},
{&Bucket{Capacity: 5, Volume: 1}, &Bucket{Capacity: 3, Volume: 1}, 0, 2},
{&Bucket{Capacity: 5, Volume: 0}, &Bucket{Capacity: 3, Volume: 0}, 0, 0},
{&Bucket{Capacity: 5, Volume: 5}, &Bucket{Capacity: 3, Volume: 3}, 5, 3},
{&Bucket{Capacity: 5, Volume: 4}, &Bucket{Capacity: 3, Volume: 2}, 3, 3},
}
for _, tc := range testcases {
tc.source.Pour(tc.target)
if tc.source.Volume != tc.expectedSrcVol {
t.Errorf("expected source volume %d, got = %d", tc.expectedSrcVol, tc.source.Volume)
}
if tc.target.Volume != tc.expectedTargetVol {
t.Errorf("expected target volume %d, got = %d", tc.expectedTargetVol, tc.target.Volume)
}
}
}
Loading…
Cancel
Save