JS :: Building prompts with Array.reduce and Object.assign


#1

Array.reduce is the swiss army penknife of Javascript.

It simply lets us:

  • start with a seed value, and
  • work through a list item by item – updating the seed value each time.

and it turns out that all manner of things can be done in this way, sparing us from manually setting up loops and iterator values, and protecting us from all the boundary condition accidents and puzzles that loops are heir to.

One use of Array.reduce in Drafts is in creating a prompt from a list of button names.

For the initial seed value, we can use the standard JS Object.assign to return a prompt object with any title etc properties that we need.

For each stage of working through the button list, we define a function with two arguments (accumulator, item), or (a, x).

  • The accumulator is the current state of the changing seed value
  • the item, in this case, is a button name.

Our function just adds a button, and returns the updated prompt.

// A prompt for selecting an item from a list.
const p = categories.reduce(

    // Accumulator updates - a button added for each category in the list:
    (prompt, buttonName) => {
        prompt.addButton(buttonName);
        return prompt;
    },

    // Initial accumulator: a prompt with properties:
    Object.assign(
        Prompt.create(), {
            title: 'Select list:',
            message: 'Ask for a category, and append' +
                ' to a tagged list for that category',
            isCancellable: true
        }
    )
);

#2

This I think requires a big conceptual shift, at least for me, but I think I see the logic. I was completely confused by another code example you posted b/c of the initial const … but presumably this is all creating the object. I’m not sure it’s the easiest code to follow for newcomers but I am intrigued by the approach.


#3

My feeling is that if you are starting out afresh, the mental model provided by

  • map
  • reduce
  • filter

is probably simpler than that of having to set up loops, increment mutable variables, check boundary conditions etc etc.

(It certainly brings down the bug count, by handing the mechanics over to pre-built parts).

If, however, we are already very used to loops and actions, then composing values does involve a bit of a mental shift.


#4

Incidentally, the full context of that snippet might make things clearer – you should find it by expanding the disclosure triangle in this post: