madbernard: a long angled pier (Default)
[personal profile] madbernard
Last evening I had a moment and tried the Coderbyte challenge "when given a string of single letters, plusses, and equals signs, return true only if every letter has a plus on both sides". I came up with a four part if statement reliant on regexes.
function SimpleSymbols(str) {
  if (/(\+\w\+)+/g.test(str) && !/^\w/g.test(str) && !/=\w/g.test(str) && !/\w(?!\+)/g.test(str)) 
  {return true;}
  else {return false;}
In English, that's if there is a plus on either side of a letter, and if there is no letter at the start of the string, and if there is no letter with an equals sign immediately in front of it, and if there is no letter that is not followed by a plus sign... Then true.

Ben, who does JS for a living, gave me the learning that if there's more than one regex, it's probably not ideal... "There's so many edge cases". Makes sense. So, later, the Coderbyte challenge appears, "when given a string of lowercase letters, if there is an a followed by a b three spots later, return true". And I'm like, "I'll use a for loop, like we were talking about last night!"
function ABCheck(str) {
  var foo = false;
  for (var i = 0; i < (str.length - 4); i++) {
    if (str.charAt(i) === 'a') {
      if (str.charAt(i + 4) === 'b') {
        foo = true;      
  return foo;       
I had trouble with the if statements inside the loop because they had returns in them that stopped the looping, and it took a while to sort that out. And then I go find better answers, and there's Matt Larsh with:
function ABCheck(str) { 
  return /a...b/g.test(str);
...Yep, not yet a RegEx whiz, here.

But the middle three challenges were so trivial that I still feel fine. Pretty much everyone I checked got the same basic answer for "if num2 is bigger than num1 return true" and "given a number of minutes return an hour:minute shaped answer". I did the most elegant thing possible for "take a string and return it sorted alphbetically", because that's one where "ARR4RYS 4EV4AR" is in fact the answer:
function AlphabetSoup(str) {
  return str.split('').sort().join(''); 

May 2016

8910 11121314

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Sep. 22nd, 2017 06:58 pm
Powered by Dreamwidth Studios