Coderbyte easy 5 and 6
Aug. 11th, 2015 05:10 pm![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
Challenge 5 was, given a number between 1 and 1000, add up all the numbers inclusive in that set. Obviously I could repurpose Matt Larsh's recursive function to do this, so I did so, and it worked first try. Woo! Though, no one else seems to be doing +=. I wonder if this would be super wrong if I wasn't recursing and thus seeing it only once each function call? Or do they just like num + SimpleAdding(stuff)?
One of my abandoned paths was to do a str.replace(regex, function) but I wasn't getting the function to work... So I was super curious to see what Matt Larsh did, and sure enough he did something cool:
function SimpleAdding(num) { if (num === 1) { return 1; } else { return num += SimpleAdding(num - 1); } }Challenge 6 was one I hadn't yet solved in Free Code Camp: Capitalize every word in a string. I abandoned a couple different paths while trying for speed, and eventually came up with this answer that seems cludgy:
function LetterCapitalize(str) { var foo = str.split(''); var bar = []; bar.push(foo[0].toUpperCase()); for(var i = 1; i < foo.length; i++) { if (foo[i - 1] === ' ') { bar.push(foo[i].toUpperCase()); } else { bar.push(foo[i]); } } console.log(bar.join('')); return bar.join(''); } LetterCapitalize('to see how to enter arguments in JavaScript');I tried replacing the space in the if statement with /\s/ and that didn't work, nor did /\s/g; I'm not sure why not.
One of my abandoned paths was to do a str.replace(regex, function) but I wasn't getting the function to work... So I was super curious to see what Matt Larsh did, and sure enough he did something cool:
function LetterCapitalize(str) { return str.replace(/\b[a-z]/g,function(c){return c.toUpperCase()}); }That "\b" was something I thought should exist, but didn't find: the signal for "match a word boundary". I just tried /\b\w/g and that works, too; I suppose his way is better, though, since it limits the capitalization to only things that we absolutely know need capitalizing. Unless if \w includes accented letters and other slightly less usual things? My RegEx skillz are not yet l33t and m4d.