/**
* Simple message queue decoder.
* Handles basic encoding/decoding for demonstration purposes.
*/
class MessageDecoder {
/**
* Decodes a message.
* @param {string} encodedMessage The encoded message.
* @param {string} encodingType The type of encoding used (e.g., "base64", "hex").
* @returns {string} The decoded message, or null if decoding fails.
*/
decode(encodedMessage, encodingType) {
try {
switch (encodingType.toLowerCase()) {
case "base64":
return atob(encodedMessage); // Basic Base64 decoding
case "hex":
return decodeHex(encodedMessage); //decode hex string
default:
console.warn("Unsupported encoding type:", encodingType);
return null;
}
} catch (error) {
console.error("Decoding error:", error);
return null;
}
}
/**
* Helper function to decode a hexadecimal string.
* @param {string} hexString The hexadecimal string to decode.
* @returns {string} The decoded string.
*/
decodeHex(hexString) {
const hexValues = hexString.match(/([0-9a-fA-F]{2})/g);
if (!hexValues) return "";
return Array.from(hexValues).map(hex => String.fromCharCode(parseInt(hex, 16))).join("");
}
}
// Example Usage (for testing)
// const decoder = new MessageDecoder();
// const encoded = "SGVsbG8gV29ybGQh"; // Base64 encoded "Hello World!"
// const decoded = decoder.decode(encoded, "base64");
// console.log("Decoded:", decoded); // Output: Decoded: Hello World!
// const hexEncoded = "48656c6c6f20576f726c64"; // Hex encoded "Hello World!"
// const decodedHex = decoder.decode(hexEncoded, "hex");
// console.log("Decoded Hex:", decodedHex); // Output: Decoded Hex: Hello World!
Add your comment