Skip to content

Instantly share code, notes, and snippets.

@Sigafoos Sigafoos/todo.js

Last active Sep 30, 2019
Embed
What would you like to do?
JavaScript to parse todo.txt (todotxt.org) formatted todos into objects
const date = '\\d{4}-\\d{2}-\\d{2}',
contextre = /\B@\w+/g;
projectre = /\B\+\w+/g,
tagre = /[\w\-_]+:[\w\-_]+/g;
const pluckAll = (raw, re) => {
let matches = raw.match(re);
if (matches) {
matches.forEach(p => {
let position = raw.indexOf(p);
raw = raw.substr(0, position) + raw.substr(position + p.length);
});
}
return [raw, matches];
}
const parse = raw => {
let todo = {};
if (raw.indexOf('x ') === 0) {
todo.done = true;
raw = raw.substr(2);
let completed = new RegExp('^' + date + ' ').exec(raw);
if (completed) {
todo.completed = completed[0].trim();
raw = raw.substr(11);
}
}
let priority = /^\(([a-z])\) /.exec(raw);
if (priority) {
todo.priority = priority[1].toUpperCase()
raw = raw.substr(4);
}
let created = new RegExp('^' + date + ' ').exec(raw);
if (created) {
todo.created = created[0].trim();
raw = raw.substr(11);
}
let projects = [];
[raw, projects] = pluckAll(raw, projectre);
if (projects) {
todo.projects = projects;
}
let contexts = [];
[raw, contexts] = pluckAll(raw, contextre);
if (contexts) {
todo.contexts = contexts;
}
let tags = [];
[raw, tags] = pluckAll(raw, tagre);
if (tags) {
tags.forEach(t => {
let [k, v] = t.split(':');
todo[k] = v;
});
}
raw = raw.trim();
raw = raw.replace(/\s{2,}/g, ' ');
todo.text = raw;
return todo;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.