1. /**
  2. * Simple message queue decoder.
  3. * Handles basic encoding/decoding for demonstration purposes.
  4. */
  5. class MessageDecoder {
  6. /**
  7. * Decodes a message.
  8. * @param {string} encodedMessage The encoded message.
  9. * @param {string} encodingType The type of encoding used (e.g., "base64", "hex").
  10. * @returns {string} The decoded message, or null if decoding fails.
  11. */
  12. decode(encodedMessage, encodingType) {
  13. try {
  14. switch (encodingType.toLowerCase()) {
  15. case "base64":
  16. return atob(encodedMessage); // Basic Base64 decoding
  17. case "hex":
  18. return decodeHex(encodedMessage); //decode hex string
  19. default:
  20. console.warn("Unsupported encoding type:", encodingType);
  21. return null;
  22. }
  23. } catch (error) {
  24. console.error("Decoding error:", error);
  25. return null;
  26. }
  27. }
  28. /**
  29. * Helper function to decode a hexadecimal string.
  30. * @param {string} hexString The hexadecimal string to decode.
  31. * @returns {string} The decoded string.
  32. */
  33. decodeHex(hexString) {
  34. const hexValues = hexString.match(/([0-9a-fA-F]{2})/g);
  35. if (!hexValues) return "";
  36. return Array.from(hexValues).map(hex => String.fromCharCode(parseInt(hex, 16))).join("");
  37. }
  38. }
  39. // Example Usage (for testing)
  40. // const decoder = new MessageDecoder();
  41. // const encoded = "SGVsbG8gV29ybGQh"; // Base64 encoded "Hello World!"
  42. // const decoded = decoder.decode(encoded, "base64");
  43. // console.log("Decoded:", decoded); // Output: Decoded: Hello World!
  44. // const hexEncoded = "48656c6c6f20576f726c64"; // Hex encoded "Hello World!"
  45. // const decodedHex = decoder.decode(hexEncoded, "hex");
  46. // console.log("Decoded Hex:", decodedHex); // Output: Decoded Hex: Hello World!

Add your comment