Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JavaScript Functions: Cracking the Code

DZone 's Guide to

JavaScript Functions: Cracking the Code

Learn how to use split, map, and join functions in JavaScript.

· Web Dev Zone ·
Free Resource

Our goal today is to create a simple JavaScript function that will decipher a secret message given specific criteria. Let’s take a look at our project.

The inspiration for this project came from Yvonne-liu of Codewars.

You are given a secret message that you need to decipher. Here are the things you need to know in order to decipher it:

For each word:

  • the second and the last letter is switched (e.g. Hello becomes Holle).
  • the first letter is replaced by its character code (e.g. H becomes 72).

Note: there are no special characters used, only letters and spaces.

Examples:

decipherThis('72olle 103doo 100ya'); 
decipherThis('82yade 115te 103o'); 


Define our Strategy

Before we begin, let’s think about what we know and what we need. We have a string, which serves as our secret message. The key states that the second and last letters are switched. Then, the first letter is replaced by its character code. I’ve included a table of Printable ASCII Characters and their Character Codes courtesy of W3Schools.

Char Number Description
A 65 uppercase A
B 66 uppercase B
C 67 uppercase C
D 68 uppercase D
E 69 uppercase E
F 70 uppercase F
G 71 uppercase G
H 72 uppercase H
I 73 uppercase I
J 74 uppercase J
K 75 uppercase K
L 76 uppercase L
M 77 uppercase M
N 78 uppercase N
O 79 uppercase O
P 80 uppercase P
Q 81 uppercase Q
R 82 uppercase R
S 83 uppercase S
T 84 uppercase T
U 85 uppercase U
V 86 uppercase V
W 87 uppercase W
X 88 uppercase X
Y 89 uppercase Y
Z 90 uppercase Z
a 97 lowercase a
b 98 lowercase b
c 99 lowercase c
d 100 lowercase d
e 101 lowercase e
f 102 lowercase f
g 103 lowercase g
h 104 lowercase h
i 105 lowercase i
j 106 lowercase j
k 107 lowercase k
l 108 lowercase l
m 109 lowercase m
n 110 lowercase n
o 111 lowercase o
p 112 lowercase p
q 113 lowercase q
r 114 lowercase r
s 115 lowercase s
t 116 lowercase t
u 117 lowercase u
v 118 lowercase v
w 119 lowercase w
x 120 lowercase x
y 121 lowercase y
z 122 lowercase z

Now, there are many ways to approach the problem, but we’re going to keep things simple. That being said, our strategy will be as follows:

  1.  split the string into a list of words.

  2.  Create a Javascript Function for later use that will swap the first and last characters in that list and then join that list back together

  3. Using Regular Expressions and map, we will identify any numbers within the words and then   replace them with the appropriate character code from our table in order to create another list that we will join together.  

If this seems a bit much, don’t worry I’ll be explaining each of these concepts as we go along. Let’s get started.

String.Split()

First, we’re going to start off by defining our function and our variables.

const decipherThis = (cipher) =>{
//     // SECOND AND LAST LETTERS ARE SWITCHED
//     // THE FIRST LETTER IS REPLACED WITH ITS CHARACTER CODE
    const words = cipher.split(' ');
    const char_codes = {
"65": "A", "66": "B", "67": "C","68": "D","69": "E","70": "F",
"71": "G", "72": "H","73": "I","74": "J","75": "K", "76": "L",
"77": "M","78": "N", "79": "O","80": "P", "81": "Q","82": "R", 
"83": "S","84": "T","85": "U", "86": "V", "87": "W", "88": "X", 
"89": "Y","90": "Z", "97": "a","98": "b", "99": "c","100": "d",
"101": "e","102": "f","103": "g","104": "h", "105": "i",
"106": "j","107": "k","108": "l","109": "m","110": "n","111": "o",
"112": "p","113": "q","114": "r","115": "s", "116": "t","117": "u",    
"118": "v","119": "w","120": "x","121": "y","119": "w","120": "x",
"121": "y","122": "z"
};


After we’ve defined our function, we created the variable, words, using our input string, cipher, and called the split function.

The split JavaScript function is used to split the given string into an array of strings by separating it into substrings using a specified separator provided in the argument.

The syntax of the function is as follows:

string.split(separator, limit)


Arguments

The first argument to this function is a string, which specifies the points where the split has to take place. This argument can be treated as a simple string or as a regular expression. As a result, if the separator is unspecified, the entire string becomes one single array element. The same thing also happens when the separator is not present in the string. If the separator is an empty string (“”), every character of the string is separated.

The second argument to the function limit defines the upper limit on the number of splits to be found in the given string. If the string remains unchecked after the limit is reached, then it is not reported in the array.

Take a look at the following examples

> const cipher = '82yade 115te 103o'
> cipher.split(' ')
[ '82yade', '115te', '103o' ]
> const word = '82yade'
> word.split('')
[ '8', '2', 'y', 'a', 'd', 'e' ]


As you can see in our first example, by using a space as our separator, we were able to create an array of elements based on the spaces within the string. Within the second example, since we simply used an empty string, the array that was created consisted of every character within the string. It’s important to know that the split function will only work on a string.

Let’s go back to our JavaScript function.

Using our table of character codes, we created an object char_codes consisting of key, value pairs for both uppercase and lowercase letters.

Moving forward, in order to complete our next task of swapping the first and last characters within our cipher, we will create a function that we’ll call swapChar.

const swapChar = (cipher) =>{
        [text[1] , text[cipher.length - 1]] = [text[text.length - 1],text[1]]
return text.join('');
   };


The first thing we did here was define the variable, text, which consists of our input separated into an array. In order to have our first and last characters exchange places, we simply create an array consisting of the first element and last element equal to itself in reverse order. To complete the function, we call the join method on our variable and return the value.

Array.Join()

Unlike the split function, the join method returns the array as a string. The elements, instead of being split, will be separated by a specified separator. If no separator is identified, the default will be a comma (,). It’s important to note that this method will not change the original array, so you will need to call the result as a variable.

Here’s a quick example:

> const cipher = '82yade 115te 103o'
> const arr = cipher.split('')
> arr
[  '8', '2', 'y',
  'a', 'd', 'e',
  ' ', '1', '1',
  '5', 't', 'e',
  ' ', '1', '0',
  '3', 'o']
> const text = arr.join('')
> text
'82yade 115te 103o'


The join function will work as long as it is being called on an array.

> const numbers = [1,2,3,4,5,6,'hello','world']
> const arr = numbers.join('')
> const newArr = numbers.join('')
> newArr
'123456helloworld'
'123456helloworld'


We’ve broken down our secret message into an array called words which contains the individual characters. We also created a function that will swap the first character in the array with the last once called.

const newCipher = words.map(word =>{
   let charCode = String(word.match(/\d+/g).map(Number))


Array.Map()

When we call the map method, we’re able to create a new array with the results of calling a function for every array element. The map method calls the provided function once for each element in the array in order.

Here, define a new function that will locate any number within the string using RegExp. Using the map method, we will be able to create a list from our results.

In our example, the map method will search each element in the words array for a number (word) and add it to the new array newCipher

As a result, it is important to note that the map method does not execute the function for elements that have no values. Also, the method will not alter the original array, so it's important to assign the function to a new variable.

For more information on the map and its applications, GeeksforGeeks is an excellent resource.            

Within our JavaScript function, the first step was to identify any number within each word and then assign that to a variable. We accomplished this with RegExp or Regular Expressions.

Regular Expressions

Regular expressions or RegExp allow us to identify and extract patterns within a string. The pattern can be any particular word or phrase that is repeated within the string. It can be a group of numbers separated by symbols like phone numbers. The expression can even be in the format of an email.

Really, the possibilities are endless. As long as the string consists of a pattern, you will be able to make use of Regular Expressions. Discussing Regular Expressions will go beyond the scope of this article but I highly recommend you check using Regular Expressions within your code as it will save you tons of time. CodeBurst has a really good breakdown of the syntax involved, as well as some examples to get you started.

In our code, we extracted each number from every word in our array. Our next step, using that number is to call the character for that number and replace it with the last character.

return word.replace(charCode,char_codes[charCode])});


Conclusion

Here, we replace the matched number with the character code from our character code object and return the newly constructed array.

const result = newCipher.map(str =>{
     return swapChar(str)});
   return result.join(' ');
 }


In conclusion, using the swapChar function that we defined we exchange the first and last elements and then join making sure to use a space as the separator. Our result is the deciphered message.

decipherThis('72olle 103doo 100ya'); // 'Hello good day'
decipherThis('82yade 115te 103o'); // 'Ready set go'


If you’re interested in seeing a more efficient and cleaner way to accomplish the same task using other JavaScript functions, or if there are any projects that you would like to see in the future, I’d be happy to hear from you.  

Topics:
web dev ,javascript ,ascii ,split function ,join function ,map functino ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}