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
}
)
);