Skip to content

Instantly share code, notes, and snippets.

@srph
Created April 18, 2019 02:50
Show Gist options
  • Save srph/8439d49a129ee3e8a44c9b5a841ef641 to your computer and use it in GitHub Desktop.
Save srph/8439d49a129ee3e8a44c9b5a841ef641 to your computer and use it in GitHub Desktop.
JS: Example code to get number of consecutive dates
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