Codewars - Valid Spacing - 7kyu
Aldi Duzha / December 28, 2020
2 min read • ––– views
Question:
Your task is to write a function called valid_spacing()
or validSpacing()
which checks if a string has valid spacing. The function should return either True
or False
.
For this kata, the definition of valid spacing is one space between words, and no leading or trailing spaces. Below are some examples of what the function should return.
Test Cases
const sentence = 'Hello World ';
const sentence2 = 'Hello world';
const sentence3 = ' Hello world';
const sentence4 = 'Hello world ';
const sentence5 = 'Hello world';
const sentence6 = 'Hello';
const sentence7 = '';
const sentence8 = ' ';
console.log(validSpacing(sentence)); // false
console.log(validSpacing(sentence2)); // true
console.log(validSpacing(sentence3)); // false
console.log(validSpacing(sentence4)); // false
console.log(validSpacing(sentence5)); // true
console.log(validSpacing(sentence7)); // true
console.log(validSpacing(sentence8)); // false
Best Solution
- Replace occurrences of 2 or more spaces with 1 space
- Trim leading and trailing whitespaces
- Compare the modified string with the original string
const validSpacing = (sentence) => {
return sentence.replace(/\s{2,}/g, ' ').trim() === sentence;
};
Alternative Solution 1
- Check if the string starts or ends with a space, or if there are more than 2 spaces together.
const validSpacing = (sentence) => {
return !/^[\s]|[\s]{2,}|[\s]$/g.test(sentence);
};
Alternative Solution 2
- Check if the input is null or starts with a space.
- Check if the remaining string consists of 0 or more (space and word) groups.
const validSpacing = (sentence) => {
return !s || /^\w+( \w+)*$/.test(s);
};
Verbose Solution
We use two regex patterns to identify spaces and words. Then, we use two if statements to verify the presence of words and spaces. Finally, we return True if the number of words matches the number of spaces minus one, since a sentence has one less space than the number of words.
const validSpacing = (sentence) => {
const spaceRegex = /\s/gi;
const wordRegex = /[a-z]+/gi;
if (sentence.match(spaceRegex) == null || sentence.length == 0) {
return true;
} else if (sentence.match(wordRegex) == null) {
return false;
} else if (
sentence.match(spaceRegex).length ==
sentence.match(wordRegex).length - 1
) {
return true;
}
return false;
};