DEV Community

Cesar Del rio
Cesar Del rio

Posted on • Updated on

#10 - Valid Spacing CodeWars Kata (7 kyu)

Instructions

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.

Examples:

'Hello world' = true
' Hello world' = false
'Hello world ' = false
'Hello world' = false
'Hello' = true
// Even though there are no spaces, it is still valid because none are needed
'Helloworld' = true
// true because we are not checking for the validity of words.
'Helloworld ' = false
' ' = false
'' = true


Note - there will be no punctuation or digits in the input string, only letters.

My solution:

function validSpacing(s) {
  return s=='' ? true : s.split(' ').find(el=> el=='') >= 0 ? false : true
}

Enter fullscreen mode Exit fullscreen mode

Explanation

I returned the values using a ternary operator, so first I used a conditional that if the string is empty it will return true, then I used another conditional in which I splitted into an array the string between every space and then I used the find method, so if it finded an element that had an empty space it means that the spacing is not correct and it returned false, else it'll return true

Comment how would you solve this kata and why? 👇🤔

My Github
My twitter
Solve this Kata

Top comments (0)