api tweaks.

This commit is contained in:
Will Charczuk 2017-04-29 23:17:28 -07:00
parent 674e75d285
commit 1c1430e3b8
4 changed files with 75 additions and 6 deletions

View File

@ -1,5 +1,10 @@
package sequence
// NewArray creates a new array.
func NewArray(values ...float64) Array {
return Array(values)
}
// Array is a wrapper for an array of floats that implements `ValuesProvider`.
type Array []float64

View File

@ -176,7 +176,6 @@ func TestNewBufferWithValues(t *testing.T) {
values := NewBuffer(1, 2, 3, 4, 5)
assert.NotNil(values)
assert.Equal(5, values.Len())
assert.Equal(bufferDefaultCapacity, values.Capacity())
assert.Equal(1, values.Peek())
assert.Equal(5, values.PeekBack())
}

View File

@ -36,6 +36,10 @@ func (s Seq) FoldLeft(mapfn func(i int, v0, v float64) float64) (v0 float64) {
return 0
}
if s.Len() == 1 {
return s.GetValue(0)
}
v0 = s.GetValue(0)
for i := 1; i < s.Len(); i++ {
v0 = mapfn(i, v0, s.GetValue(i))
@ -49,7 +53,12 @@ func (s Seq) FoldRight(mapfn func(i int, v0, v float64) float64) (v0 float64) {
return 0
}
for i := s.Len() - 1; i >= 0; i-- {
if s.Len() == 1 {
return s.GetValue(0)
}
v0 = s.GetValue(s.Len() - 1)
for i := s.Len() - 2; i >= 0; i-- {
v0 = mapfn(i, v0, s.GetValue(i))
}
return

View File

@ -9,19 +9,75 @@ import (
func TestSequenceEach(t *testing.T) {
assert := assert.New(t)
values := Seq{Array([]float64{1, 2, 3, 4})}
values := Seq{NewArray(1, 2, 3, 4)}
values.Each(func(i int, v float64) {
assert.Equal(i, v)
assert.Equal(i, v-1)
})
}
func TestSequenceMap(t *testing.T) {
assert := assert.New(t)
values := Seq{Array([]float64{1, 2, 3, 4})}
values := Seq{NewArray(1, 2, 3, 4)}
mapped := values.Map(func(i int, v float64) float64 {
assert.Equal(i, v)
assert.Equal(i, v-1)
return v * 2
})
assert.Equal(4, mapped.Len())
}
func TestSequenceFoldLeft(t *testing.T) {
assert := assert.New(t)
values := Seq{NewArray(1, 2, 3, 4)}
ten := values.FoldLeft(func(_ int, vp, v float64) float64 {
return vp + v
})
assert.Equal(10, ten)
orderTest := Seq{NewArray(10, 3, 2, 1)}
four := orderTest.FoldLeft(func(_ int, vp, v float64) float64 {
return vp - v
})
assert.Equal(4, four)
}
func TestSequenceFoldRight(t *testing.T) {
assert := assert.New(t)
values := Seq{NewArray(1, 2, 3, 4)}
ten := values.FoldRight(func(_ int, vp, v float64) float64 {
return vp + v
})
assert.Equal(10, ten)
orderTest := Seq{NewArray(10, 3, 2, 1)}
notFour := orderTest.FoldRight(func(_ int, vp, v float64) float64 {
return vp - v
})
assert.Equal(-14, notFour)
}
func TestSequenceSum(t *testing.T) {
assert := assert.New(t)
values := Seq{NewArray(1, 2, 3, 4)}
assert.Equal(10, values.Sum())
}
func TestSequenceAverage(t *testing.T) {
assert := assert.New(t)
values := Seq{NewArray(1, 2, 3, 4)}
assert.Equal(2.5, values.Average())
valuesOdd := Seq{NewArray(1, 2, 3, 4, 5)}
assert.Equal(3, valuesOdd.Average())
}
func TestSequenceVariance(t *testing.T) {
assert := assert.New(t)
values := Seq{NewArray(1, 2, 3, 4, 5)}
assert.Equal(2, values.Variance())
}