How about this logic?
- if the first character or last character is a letter it's false
- then go through the array and look for the letters
- skip it if is a
=
or a +
- if it isn't a
=
or a +
then check that the character before and after is a +
So something like this:
var simpleSymbols = function (s) { if (s[0] != "+" && s[0] != "=") { return false; } else if (s[s.length - 1] != "+" && s[s.Length - 1] != "=") { return false; } else { for (var i = 1; i<s.Length - 1; i++) { if (s[i] != "+" && s[i] != "=") { if (s[i-1] != "+" || s[i+1] != "+") { return False; } } } } return true; }
This code is cleaner than what you have.
With this block of code:
- it's more readable
- it exits if the first or last character is a letter, immediately preventing unnecessary iterations in a for loop.
- it's easier to read
- it's easier to follow (in my opinion)
Bottom Line
Your code is not efficient. All of the if
statements fire every iteration until the end of the string is met or a return is met.
- if the last character is a letter, will return false and not loop through the whole string.
- will not perform a "before and after check" unless the character is a letter
It may not make a difference in smaller strings, but if you have a huge string to parse, it will make a difference.
I have been told the the CoderBytes challenge will include numbers that don't need to be surrounded by +
's, and I wanted to steal a little of @Konijn's answer as well.
All of my above points still stand for this code block as well.
var simpleSymbols = function (s) { if (s[0] >= 'a' || s[s.length -1] >= 'a') { return false; } else { for (var i = 1; i<s.length - 1; i++) { if (s[i] >= 'a') { if (s[i-1] != "+" || s[i+1] != "+") { return false; } } } } return true; }
NOTE
This code is the most efficient way to perform this task.
It exits if the first or last character is a letter because you can't have a +
before the first character or a +
after the last character, thus failing the filter.
It only checks the before and after characters if the character is a letter. This prevents unnecessary if statements from being performed
All the other answers so far will check every character and the before and after character until it return
s. This could be an issue if the string is say 500,000 characters long, you would see a definite decrease in performance.
This code will not loop through the whole string if there is a letter in the last character position, which would make it a lot more efficient in those cases.