1. /**
  2. * Compresses message queue output for validation checks with inline comments.
  3. *
  4. * @param {Array<string>} messages An array of message strings from a queue.
  5. * @param {string} [delimiter=', '] Delimiter between messages. Defaults to ', '.
  6. * @returns {string} A single string containing the compressed messages.
  7. */
  8. function compressMessages(messages, delimiter = ', ') {
  9. if (!Array.isArray(messages)) {
  10. return ""; // Handle invalid input
  11. }
  12. const formattedMessages = messages.map(message => {
  13. // Escape special characters for safe string concatenation
  14. return message.replace(/[&<>"']/g, '\\$&');
  15. });
  16. const joinedString = formattedMessages.join(delimiter);
  17. // Add inline comments for readability and validation
  18. let compressedString = "";
  19. for (let i = 0; i < joinedString.length; i++) {
  20. compressedString += joinedString[i];
  21. if ((i + 1) % 10 === 0 && i < joinedString.length - 1) {
  22. // Add a newline after every 10 characters for readability
  23. compressedString += "\n";
  24. }
  25. }
  26. return compressedString;
  27. }
  28. //Example Usage:
  29. // const messages = ["Hello, world!", "This is a test.", "Another message"];
  30. // const compressed = compressMessages(messages);
  31. // console.log(compressed);
  32. // const compressedWithCustomDelimiter = compressMessages(messages, '; ');
  33. // console.log(compressedWithCustomDelimiter);

Add your comment