/**
* Compresses message queue output for validation checks with inline comments.
*
* @param {Array<string>} messages An array of message strings from a queue.
* @param {string} [delimiter=', '] Delimiter between messages. Defaults to ', '.
* @returns {string} A single string containing the compressed messages.
*/
function compressMessages(messages, delimiter = ', ') {
if (!Array.isArray(messages)) {
return ""; // Handle invalid input
}
const formattedMessages = messages.map(message => {
// Escape special characters for safe string concatenation
return message.replace(/[&<>"']/g, '\\$&');
});
const joinedString = formattedMessages.join(delimiter);
// Add inline comments for readability and validation
let compressedString = "";
for (let i = 0; i < joinedString.length; i++) {
compressedString += joinedString[i];
if ((i + 1) % 10 === 0 && i < joinedString.length - 1) {
// Add a newline after every 10 characters for readability
compressedString += "\n";
}
}
return compressedString;
}
//Example Usage:
// const messages = ["Hello, world!", "This is a test.", "Another message"];
// const compressed = compressMessages(messages);
// console.log(compressed);
// const compressedWithCustomDelimiter = compressMessages(messages, '; ');
// console.log(compressedWithCustomDelimiter);
Add your comment