Practical work: use functions in javascript

Task: make two functions that codes and decodes text

Implementation in Javascript:

Code

        //This is a cipher
        const cod = {
            'A': 'Z', 'B': 'Y', 'C': 'X', 'D': 'W', 'E': 'V', 'F': 'U', 'G': 'T', 
            'H': 'S', 'I': 'R', 'J': 'Q','K': 'P', 'L': 'O', 'M': 'N', 'N': 'M',                              
            'O': 'L', 'P': 'K', 'Q': 'J', 'R': 'I', 'S': 'H', 'T': 'G',                                                            
            'U': 'F', 'V': 'E', 'W': 'D', 'X': 'C', 'Y': 'B', 'Z': 'A',

            'a': 'z', 'b': 'y', 'c': 'x', 'd': 'w', 'e': 'v', 'f': 'u', 'g': 't',   
            'h': 's', 'i': 'r', 'j': 'q','k': 'p', 'l': 'o', 'm': 'n', 'n': 'm',    
            'o': 'l', 'p': 'k', 'q': 'j', 'r': 'i', 's': 'h', 't': 'g',
            'u': 'f', 'v': 'e', 'w': 'd', 'x': 'c', 'y': 'b', 'z': 'a',
        };

        //Functions
        //This function encodes the text
        function coder(text) {
            let result = "";
            for (let i = 0; i < text.length; i++) {
                var t = text[i]
                var l = cod[t]
                result += l || t
            }
            return result;
        }

        //This function decodes the text
        function decoder(text) {
            let result = "";
            for (let i = 0; i < text.length; i++) {
                var t = text[i]
                let l = Object.keys(cod).find(k => cod[k] === t);
                result += l || t
            }
            return result;
        }

        // Main code
        let text = 'Hello world!!!';
        let codedText = coder(text)
        let decodedText = decoder(codedText)

        //Output to the console coded and decodes texts
        console.log("Сoded text:" + codedText);
        console.log("Decoded text:" + decodedText);

Result:

If you have more tasks or exercises, please write them in the comments.

Thank you, good bye!

Leave a Reply

Your email address will not be published. Required fields are marked *




Enter Captcha Here :