From 1372f9edc096ed8f2bfceb758e7e0bba3adc9cf5 Mon Sep 17 00:00:00 2001 From: Hoang Trinh Date: Wed, 7 Jun 2023 08:57:59 +0700 Subject: [PATCH] fix: correct nearest current tick when current tick is below smallest (#5) * fix: correct nearest current tick when current tick is below smallest * test: add ut for nearest current ticks --------- Co-authored-by: Ha Nguyen --- entities/ticklist.go | 9 +++++++++ entities/ticklist_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/entities/ticklist.go b/entities/ticklist.go index 6541a59..c113545 100644 --- a/entities/ticklist.go +++ b/entities/ticklist.go @@ -189,6 +189,15 @@ func NextInitializedTickWithinOneWord(ticks []Tick, tick int, lte bool, tickSpac } func GetNearestCurrentTick(ticks []Tick, currentTick int) (int, error) { + isBelowSmallest, err := IsBelowSmallest(ticks, currentTick) + if err != nil { + return utils.MinTick, err + } + + if isBelowSmallest { + return utils.MinTick, nil + } + tick, err := NextInitializedTick(ticks, currentTick, true) if err != nil { return TickIndexZero, err diff --git a/entities/ticklist_test.go b/entities/ticklist_test.go index 4b2e0a5..3027c8d 100644 --- a/entities/ticklist_test.go +++ b/entities/ticklist_test.go @@ -143,3 +143,37 @@ func TestNextInitializedTickWithinOneWord(t *testing.T) { } } + +func TestGetNearestCurrentTick(t *testing.T) { + testCases := []struct { + name string + ticks []Tick + currenTick int + expectedResult int + expectedError error + }{ + { + name: "it should return minTicks with error when currentTick is min tick and ticks is empty", + ticks: []Tick{}, + currenTick: utils.MinTick, + expectedResult: utils.MinTick, + expectedError: ErrEmptyTickList, + }, + { + name: "it should return minTicks with no error when currentTick is min tick and ticks is not empty", + ticks: []Tick{lowTick, midTick, highTick}, + currenTick: utils.MinTick, + expectedResult: utils.MinTick, + expectedError: nil, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + result, err := GetNearestCurrentTick(tc.ticks, tc.currenTick) + + assert.Equal(t, tc.expectedResult, result) + assert.ErrorIs(t, err, tc.expectedError) + }) + } +}