If we have narrowed down to a small list of drafts using Draft.query, we may still need to choose one particular draft.
Rather than looping through the query harvest for a match, we can get its index directly (or learn immediately that there are no matches), using the standard JS Array.findIndex method.
findIndex returns either:
the index of the first match for the condition supplied (in a given array), or
the value -1, if there is no match.
So, for example, using first Draft.query, and then Array.findIndex:
const
category = p.buttonPressed,
// query for list drafts...
drafts = Draft.query(category, 'inbox', [listTag]),
// index of first draft that matches a condition
iDraft = drafts.findIndex(
draft => draft.content.startsWith('## ' + category)
),
d = iDraft !== -1 ? (
drafts[iDraft]
) : Object.assign(
Draft.create(), {
content: '## ' + category + '\n\n'
});
All of these could be let or var declarations, but as they don’t mutate they can each be const (fractionally faster as it happens, but mainly you get a useful warning if you inadvertently try to overwrite their value).
I prefer to group const or let declarations together (var is more or less redundant in ES6), but it could instead be written as a series of separate const declarations.
Essentially we are just binding all the names that we will need in the return section.
This is absolutely wonderful but I have to admit it’s going a bit fast for me!
These are the times when I regret having a wife and child and look back fondly on the days when I could spend literally the entirety of my free time on something like this. But at the moment I’m having to pop in and try to stay in the loop.