2016-01-19 21:11:20 -05:00
|
|
|
import moment from 'moment-timezone';
|
2015-12-10 14:52:09 -08:00
|
|
|
import { dayCount } from '../utils/date-utils';
|
|
|
|
|
|
|
|
const daysBetween = 1.5;
|
|
|
|
|
2016-01-19 21:11:20 -05:00
|
|
|
export function calcCurrentStreak(cals, timezone = 'UTC') {
|
2015-12-10 14:52:09 -08:00
|
|
|
const revCals = cals.slice().reverse();
|
|
|
|
|
2016-01-19 21:11:20 -05:00
|
|
|
if (dayCount([moment().tz(timezone), revCals[0]], timezone) > daysBetween) {
|
2015-12-10 14:52:09 -08:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
let streakBroken = false;
|
|
|
|
const lastDayInStreak = revCals
|
|
|
|
.reduce((current, cal, index) => {
|
|
|
|
const before = revCals[index === 0 ? 0 : index - 1];
|
|
|
|
if (
|
|
|
|
!streakBroken &&
|
2016-01-19 21:11:20 -05:00
|
|
|
moment(before).tz(timezone).diff(cal, 'days', true) < daysBetween
|
2015-12-10 14:52:09 -08:00
|
|
|
) {
|
|
|
|
return index;
|
|
|
|
}
|
|
|
|
streakBroken = true;
|
|
|
|
return current;
|
|
|
|
}, 0);
|
|
|
|
|
|
|
|
const lastTimestamp = revCals[lastDayInStreak];
|
2016-01-19 21:11:20 -05:00
|
|
|
return dayCount([moment().tz(timezone), lastTimestamp], timezone);
|
2015-12-10 14:52:09 -08:00
|
|
|
}
|
|
|
|
|
2016-01-19 21:11:20 -05:00
|
|
|
export function calcLongestStreak(cals, timezone = 'UTC') {
|
2015-12-10 14:52:09 -08:00
|
|
|
let tail = cals[0];
|
|
|
|
const longest = cals.reduce((longest, head, index) => {
|
|
|
|
const last = cals[index === 0 ? 0 : index - 1];
|
|
|
|
// is streak broken
|
2016-01-19 21:11:20 -05:00
|
|
|
if (moment(head).tz(timezone).diff(last, 'days', true) > daysBetween) {
|
2015-12-10 14:52:09 -08:00
|
|
|
tail = head;
|
|
|
|
}
|
2016-01-19 21:11:20 -05:00
|
|
|
if (dayCount(longest, timezone) < dayCount([head, tail], timezone)) {
|
2015-12-10 14:52:09 -08:00
|
|
|
return [head, tail];
|
|
|
|
}
|
|
|
|
return longest;
|
|
|
|
}, [cals[0], cals[0]]);
|
|
|
|
|
2016-01-19 21:11:20 -05:00
|
|
|
return dayCount(longest, timezone);
|
2015-12-10 14:52:09 -08:00
|
|
|
}
|