Brock's Bread Spread Programming Operator
This page demonstrates the use of Brock's Programming Operator, a utility function that simplifies conditional array spreading in JavaScript. I'd rather use some form of a coalesce but this acts as a holdover for the time being until the language specification can add it.
Explanation
The operator __
takes an item and returns an array containing the item if it exists, or an empty array otherwise. This is useful for conditionally adding elements to arrays.
const __=(item)=>([item]??[]); //The Brock's Programming Operator with To Use with Spreading: ...__()
Example
In the example below, the operator is used to conditionally add an optional ingredient to a sandwich:
const bread = document.createElement('div');
const pb = document.createElement('span'); pb.textContent = 'Peanut Butter';
const j = document.createElement('span'); j.textContent = 'Jelly';
const butter = document.createElement('span'); butter.textContent = 'Butter (optional)';
bread.append(pb, j, ...__(butter));
document.body.append(bread);
Another Example with a Button
In this example, the operator is used to conditionally add a button to the page:
const container = document.createElement('div');
const label = document.createElement('span'); label.textContent = 'Click the button:';
const button = document.createElement('button');
const innerSpan = document.createElement('span'); innerSpan.textContent = 'Click Me';
const optionalInner = Math.random() > 0.5 ? document.createElement('span') : null;
if (optionalInner) optionalInner.textContent = '[Optional Text Here]';
button.append(innerSpan, ...__(optionalInner));
container.append(label, button);
document.body.append(container);