JS :: Array.findIndex – simplifies use of Draft.query

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'
        });
1 Like

yeah i’m still confused as to why this is wrapped in const

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.

I’m presently at the “what does VAR mean?” Stage. :slight_smile:

1 Like

Perhaps a general primer for the basics? Maybe as a teleconference or webinar? If someone feels like they could do that or would like to do try…

It’s self serving I know, but teaching is a great way to learn. Trust me. I teach, afte a fashion, for a living. And I always learn something.

3 Likes