Created
April 18, 2019 02:50
-
-
Save srph/8439d49a129ee3e8a44c9b5a841ef641 to your computer and use it in GitHub Desktop.
JS: Example code to get number of consecutive dates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { parse, subDays } from 'date-fns'; | |
import getEntryTodayDateString from './getEntryTodayDateString' | |
import getEntryDateString from './getEntryDateString' | |
/** | |
* Get the streak between today and the last date. | |
* Assumes that there is an entry for today. | |
*/ | |
export default function getStreak(tracker: AppDataTracker): number { | |
let cursor: string = getEntryTodayDateString(tracker) | |
let streak: number = 1 | |
while (tracker.entries[cursor]) { | |
const previous = subDays(parse(cursor), 1) | |
cursor = getEntryDateString({ | |
tracker, | |
month: previous.getMonth() + 1, | |
day: previous.getDate() | |
}) | |
++streak | |
} | |
return streak | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment