Skip to content

Instantly share code, notes, and snippets.

@Ellpeck
Last active March 16, 2022 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ellpeck/9d63ea0a8edf29681e013fb7614d8b84 to your computer and use it in GitHub Desktop.
Save Ellpeck/9d63ea0a8edf29681e013fb7614d8b84 to your computer and use it in GitHub Desktop.
A simple script that can be used with Obsidian's Dataview plugin to display daily streaks of habits from your daily notes.
// For this script to work properly, each daily habit has to start with a unique emoji,
// which will also be displayed next to the daily streak for each habit.
// Daily streaks are calculated for the currently opened daily note, and end on the first day
// that the habit was not ticked off. They are displayed in order of highest to lowest length.
// To display the result of this script in your daily notes, you can use this snippet:
// ```dataviewjs
// dv.view("path/to/Obsidian Daily Streaks.js");
// ```
// This is the directory that your daily notes are in
const daily = '"path/to/daily/notes"';
let streaks = new Map();
for (let task of dv.current().file.tasks) {
let emoji = task.text.substring(0, task.text.indexOf(" "));
streaks.set(emoji, {
value: 0,
done: false
});
}
let foundToday = false;
for (let page of dv.pages(daily).sort(p => p.file.name, "desc")) {
// skip all notes that are newer than the current note
if (!foundToday) {
if (page.file.name == dv.current().file.name)
foundToday = true;
continue;
}
for (const [emoji, streak] of streaks.entries()) {
// if a streak is marked as done, it means we reached the end already
if (streak.done)
continue;
for (let task of page.file.tasks) {
if (!task.text.startsWith(emoji))
continue;
if (task.completed) {
streak.value++;
} else {
streak.done = true;
}
break;
}
}
}
// iterate streaks in order of length and display them
for (let [emoji, streak] of Array.from(streaks.entries()).sort((kv1, kv2) => kv2[1].value - kv1[1].value))
dv.span(`${emoji} ${streak.value} `);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment