From 3bc85d74fc9aee8917ffc337604b89269ab054d3 Mon Sep 17 00:00:00 2001 From: Julia Friesel Date: Thu, 7 Jun 2018 11:14:07 +0200 Subject: [PATCH] Get cycle day for day in any cycle, not just the current --- get-cycle-day-number.js | 6 +++++- test/get-cycle-day.spec.js | 29 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/get-cycle-day-number.js b/get-cycle-day-number.js index 75014a8..0864b12 100644 --- a/get-cycle-day-number.js +++ b/get-cycle-day-number.js @@ -10,7 +10,11 @@ export default function config(opts) { return function getCycleDayNumber(unsorted, targetDate) { // sort the cycle days in descending order so we travel into // the past as we iterate over the array - const cycleDays = [...unsorted].sort((a, b) => b.date.isAfter(a.date)) + // also, to retrieve the number, we only need the cycle days before the target day + // TODO we can probably rely on the db to do the sorting for us + const sorted = [...unsorted].sort((a, b) => b.date.isAfter(a.date)) + const firstDayBeforeTargetDayIndex = sorted.findIndex(day => day.date.isBefore(targetDate)) + const cycleDays = sorted.slice(firstDayBeforeTargetDayIndex) const lastPeriodStart = cycleDays.find((day, i) => { if ( diff --git a/test/get-cycle-day.spec.js b/test/get-cycle-day.spec.js index 32eefd2..87ed42d 100644 --- a/test/get-cycle-day.spec.js +++ b/test/get-cycle-day.spec.js @@ -142,6 +142,35 @@ describe('getCycleDay', () => { const result = getCycleDayNumber(cycleDays, targetDate) expect(result).to.eql(15) }) + + it('gets the correct number if the target day is not in the current cycle', () => { + const cycleDays = [{ + date: moment([2018, 5, 14]), + }, { + date: moment([2018, 5, 13]), + bleeding: { + value: 2 + } + }, { + date: moment([2018, 4, 12]), + }, { + date: moment([2018, 4, 11]), + bleeding: { + value: 2 + } + }, { + date: moment([2018, 4, 10]), + bleeding: { + value: 2 + } + }, { + date: moment([2018, 4, 9]), + }] + + const targetDate = moment([2018, 4, 27]) + const result = getCycleDayNumber(cycleDays, targetDate) + expect(result).to.eql(18) + }) }) describe('getCycleDay returns null', () => {