Skip to content

Instantly share code, notes, and snippets.

@davefowler
Last active May 29, 2025 20:32
Show Gist options
  • Select an option

  • Save davefowler/f1d92b7b7011842917c610a05fd6fd6e to your computer and use it in GitHub Desktop.

Select an option

Save davefowler/f1d92b7b7011842917c610a05fd6fd6e to your computer and use it in GitHub Desktop.
/**
* Tagged template for conditional sections with headers.
* Usage:
* - section()`Template content here` (basic template)
* - section({ header: 'Title', condition: true })`Template content here` (with header)
*/
export const prompt = (options: { header?: string; condition?: boolean } = {}) => {
return (strings: TemplateStringsArray, ...values: (string | number | undefined | null)[]): string => {
const { header, condition = true } = options;
if (!condition) {
return '';
}
// Build the content from template literal with full cleanup
const content = strings
.reduce((result, str, i) => {
const value = values[i];
const stringValue = value !== undefined && value !== null ? String(value) : '';
return result + str + stringValue;
}, '')
.replace(/\n\s*\n\s*\n/g, '\n\n') // Collapse multiple empty lines to double newlines
.replace(/^\s+|\s+$/g, '') // Trim leading/trailing whitespace
.replace(/[ \t]+/g, ' ') // Normalize spaces but preserve newlines
.replace(/\n /g, '\n') // Remove spaces after newlines
.trim();
if (!content) {
return '';
}
if (header) {
return `
==== ${header} ====
${content}
==== End of ${header} ====
`;
}
return content;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment