Solving Codewars : 7kyu alienLanguage kata

Yogita Kumar
2 min readMay 23, 2021

--

Description : Coding in function alienLanguage, function accept 1 parameter:str. Herestr is a sentence.

We translate the sentence into an alien language according to the following rules:

Each word in the sentence is separated by spaces. The last letter of each word in the sentence turns to lowercase, and the other letters are capitalized. Looks very strange? Because this is the form of alien language ;-)

for example:

alienLanguage("My name is John") should return "My NAMe Is JOHn"
alienLanguage("this is an example") should return "THIs Is An EXAMPLe"
alienLanguage("Hello World") should return "HELLo WORLd"

Solution for string "My name is John": (just replace your string)

function alienLanguage(str){
return str.split('').map(element => element.slice(0,-1).toUpperCase() + element.slice(-1).toLowerCase()).join(' ');
}

Let’s see in detail :

  1. function alienLanguage{} takes string as a parameter and store it in str variable.

2. str.split(‘ ‘) Splits the str into string array, o/p for str.split(‘ ‘) is

["My","name","is","Jhon"]

3. Now apply map() function on this string array, this method creates a new array with the results of calling a provided function on every element in this array.

Now here map() divided into parts,

element.slice(0,-1) extracts the first element through the second-to-last element in the sequence. we get

["M","nam","i","Jho"]

Then we make it all in uppercase using toUpperCase() function

So that element.slice(0,-1).toUpperCase() function in map() gives us o/p like:

["M","NAM","I","JHO"]

Now the next part from map() function takes the last character with the help of element.slice(-1) and make it in lowercase by using toLowerCase() function.

So that element.slice(-1).toLowerCase() function in map() gives us o/p like:

["y","e","s","n"]

Now just concatenate these string array element using ‘+’ sign

element.slice(0,-1).toUpperCase() + element.slice(-1).toLowerCase()

It gives o/p for map() function as:

["My", "NAMe", "Is", "JHOn"]

4. Now the last thing we need to join above string array with ‘ ‘(space) in that join() function helps us:

This method returns a new string by concatenating all of the array’s elements separated by the specified separator.

arrayFromMapFunction.join(‘ ‘);

My NAMe Is JHOn

To make code clean and nice we can pipeline our functions.The concept of pipe is simple — it combines n functions. It’s a pipe flowing left-to-right, calling each function with the output of the last one.

so altogether we can write return statement for our problem is :

function alienLanguage(str){
return str.split(' ').map(element => element.slice(0,-1).toUpperCase() + element.slice(-1).toLowerCase()).join(' ');
}

output for this is: My NAMe Is JHOn

Thank you!

--

--

Yogita Kumar

Google Developer Expert Flutter| Cloud Enthusiast | Full Stack Developer | .NET Developer |Coach and Trainer