JS :: Use Array.reduce to move done items to the end of the draft content

I get the green success banner but the draft is unchanged

Yes the function above is just a snippet which translates one string to another (within Javascript, without import from or exporting back to Drafts).

We can pull the raw string in from a draft, and then update the draft with the transformed string, by writing something like:

draft.content = (
    completedItemsToEnd(
        draft.content
    )
);
draft.update();

Or as the full code for an action:

// Completed items moved to bottom of draft
(() => {

    // main :: () -> IO Bool
    const main = () => {

        draft.content = (
            completedItemsToEnd(
                draft.content
            )
        );
        draft.update();

        console.log(true);
        return true;
    };

    // Helper function ------------------------------------

    // completedItemsToEnd :: String -> String
    const completedItemsToEnd = strDraft => {

        // dct :: { body :: [String], end :: [String] }
        const dct = strDraft.split('\n')
            .reduce(
                // Accumulator updated with every line.
                (a, line) => {
                    const isDone = line.startsWith('- [x]');
                    return {
                        body: isDone ? a.body : a.body.concat(line),
                        end: isDone ? a.end.concat(line) : a.end
                    };
                },

                // Seed value of accumulator.
                {
                    body: [],
                    end: []
                }
            );
        return dct.body.concat(dct.end).join('\n');
    };

    // MAIN -----------------------------------------------
    return main();
})()

1 Like