Javascript Codewars Problem: "Simple Pig Latin"
- Get link
- X
- Other Apps
Codewars Problem and solution with approach explained
Objective:
In this challenge, we will solve the “Simple Pig Latin” Codewars puzzle using javascript.
Problem statement:
Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched.
Examples:
Input : pigIt('Pig latin is cool');
Output : igPay atinlay siay oolcay
Input : pigIt('Hello world !');
Output: elloHay orldway !
Input : pigIt('Pig latin is cool !');
Output : igPay atinlay siay oolcay !
Solution Approach:
Step 1: capture each word of the string. Also check if there are no special characters. In case of special character that needs to be returned without any changes.
Step 2 (a): if no special character, then for each word, get the first letter and remove it from the word and add it behind the word with the string "ay".
Step 2 (b): repeat step 2 for each word and then return the final string.
Step 3 : if special characters found, skip the word and return it without any transformation.
Hint: we will use regex to find out if the word contains any special character.
Keeping these points in mind, let’s jump to the solution now:
Solution :
function pigIt(str){
var inputArr = str.split(' ');
var finalElement='';
inputArr.forEach((element, index, inputArr) => {
var regex = /[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g;
if (!regex.test(element)){
var elementArr = element.split('');
var firstElement = elementArr.shift();
if((index === inputArr.length - 1))
finalElement= finalElement+elementArr.join("")+firstElement+"ay";
else
finalElement= finalElement+elementArr.join("")+firstElement+"ay "
}
else{
finalElement= finalElement+element;
}
}
)
return finalElement;
}
- Get link
- X
- Other Apps
Comments
Nice
ReplyDelete