Last active
February 6, 2024 01:20
-
-
Save genmon/c75480d3e525b43c2e1e135d7cbb697f to your computer and use it in GitHub Desktop.
Calculating a blogging streak -- pseudocode
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
# A Monday preceding the first post on this blog. Used for calculating week numbers | |
# (Weeks start on Mondays) | |
FIRST_MONDAY = date(2000, 2, 14) | |
# Calculate week_number and streak_weeks for every post, in order. For calculating today's | |
# streak, we only need to know about the most recent post, but there's a certain amount of | |
# looking at other posts to figure that out. | |
# Note: this code looks at *all* posts because I want to calculate all streaks. For just | |
# today's streak, a quicker algorithm would run in reverse chronological order and stop at | |
# the first break. | |
current_streak = 0 | |
latest_week_number = 0 | |
most_recent_post = None | |
for post in posts_in_chronological_order: | |
post_week_number = math.floor((post.date - FIRST_MONDAY).days / 7) + 1 | |
# Figure out the streak | |
if post_week_number == latest_week_number: | |
# Same streak as previous post | |
pass | |
elif post_week_number == latest_week_number + 1: | |
# The streak is increasing! | |
current_streak += 1 | |
else: | |
# We must have missed posting for a week. Start a new streak | |
current_streak = 1 | |
# Record streak and update tracking variables | |
latest_week_number = post_week_number | |
post.streak_weeks = current_streak | |
post.week_number = post_week_number | |
most_recent_post = post | |
# Calculate today's streak. Look at today's date and the most recent post | |
today_week_number = math.floor((TODAY - FIRST_MONDAY).days / 7) + 1 | |
if today_week_number == most_recent_post.week_number: | |
# If there's a post this week, the current streak is that post's streak | |
streak_today = most_recent_post.streak_weeks | |
elif today_week_number == most_recent_post.week_number + 1: | |
# If the most recent post is *last* week, and there hasn't yet been a post this | |
# week, we can't be sure that the streak has ended (because there might be a | |
# post before the week end). So the current streak is that post's streak | |
streak_today = most_recent_post.streak_weeks | |
else: | |
streak_today = 0 | |
return streak_today |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment