Intro 🌐
I take interesting katas of all levels and explain how to solve them.
Problem solving is an important skill, for your career and your life in general.
You'd better learn to solve problems!
Source
I take the ideas for the katas from different sources and re-write them.
Today's source: Codewars
Understanding the Exercise ❗
First, we need to understand the exercise!
This is a crucial part of (software) engineering.
Go over the exercise explanation again until you understand it 100%.
Do NOT try to save time here.
My method to do this:
- Input: What do I put in?
- Output: What do I want to get out?
Today's exercise
Write a function removeExclamationMarksFromEnd
, that accepts one parameter: inputString
, a valid string.
The function should return a string. The string contains the inputString
, but without an exclamation mark at the end.
Input: a string.
Output: a string that has no exclamation mark at the end.
Thinking about the Solution 💭
I think I understand the exercise (= what I put into the function and what I want to get out of it).
Now, I need the specific steps to get from input to output.
I try to do this in small baby steps.
- have a look at the last character
- if it is a
!
, remove it - repeat from step #1 while last character is a
!
(while loop?) - return the result (a string)
Example:
- Input:
"bee!!"
- Iteration 1:
"bee!!"
// last character is!
=> remove it and repeat - Iteration 2:
"bee!"
// last character is!
=> remove it and repeat - Iteration 3:
"bee"
// last character is NOT!
=> break out of the loop - Output:
"bee"
// return the string
Implementation (while loop) ⛑
function removeExclamationMarksFromEnd(inputString) {
let result = inputString;
// run this loop while the last character is a `!`
while (result[result.length - 1] === "!") {
// remove the last character (= `!`)
result = result.slice(0, -1);
}
return result;
}
Result
console.log(removeExclamationMarksFromEnd("bee!!"));
// "bee"
console.log(removeExclamationMarksFromEnd("Hey! Bee🧶!"));
// "Hey! Bee🧶!"
Implementation (regex) ⛑
function removeExclamationMarksFromEnd(inputString) {
// use a regex (//)
// replace one or more exclamation marks (!+) from the end ($) with an empty string ("")
return inputString.replace(/!+$/, "");
}
Result
console.log(removeExclamationMarksFromEnd("bee!!"));
// "bee"
console.log(removeExclamationMarksFromEnd("Hey! Bee🧶!"));
// "Hey! Bee🧶!"
Playground ⚽
You can play around with the code here
Next Part ➡️
Great work, mate!
Next time, we'll solve the next kata. Stay tuned!
If I should solve a specific kata, shoot me a message here.
If you want to read my latest stuff, get in touch with me!
Further Reading 📖
Questions ❔
- Do you like to solve katas?
- Which implementation do you like more? Why?
- Any alternative solution?
- Do you regularly use regex?