@nvrqt03 and @alhazen1 thanks for sharing your code! Anyone else come up with different code or have questions/comments about what’s been shared so far?
Here are the next three algorithms I completed:
Boo who
My first attempt was to check if the passed in parameter equals either true or false. If it does, return true, otherwise return false:
function booWho(bool) {
return bool === true || bool === false;
}
In the Boo Who fCC Guide in hint 2, it suggests using the typeof operator, so I came up with this, which is identical to the solution in the guide:
function booWho(bool) {
return typeof bool === 'boolean';
}
Title Case a Sentence
For my first attempt, I used split(), map(), toUpperCase(), slice(), toLowerCase(), and join():
function titleCase(str) {
/*
1. str.split(' ') - Split the sentence into individual words to create an array.
2. .map(word => word[0].toUpperCase() - Take the first letter of each word and make it uppercase.
3. word.slice(1).toLowerCase() - Take the remaning letters of the word and make them lower case.
4. word[0].toUpperCase() + word.slice(1).toLowerCase() - Join the first letter with the remaining letters of the word.
5. .join(' ') - Join each word, separated by a space, into one string.
*/
return str.toLowerCase().split(' ').map(word => word[0].toUpperCase() + word.slice(1)).join(' ');
}
After thinking about this more and looking at some more built-in JavaScript methods, I came up with a way to do this using substr():
function titleCase(str) {
return str.toLowerCase().split(' ').map(word => word[0].toUpperCase() + word.substr(1)).join(' ');
}
Both solutions are relatively similar. The Title Case a Sentence fCC Guide has some other ways to do this that seem more complicated and verbose to me, but maybe they make more sense to others. I do like the regex (i.e. replace()) solution:
function titleCase(str) {
return str.toLowerCase().replace(/(^|\s)\S/g, (L) => L.toUpperCase());
}
The regex here creates a capture group (^|\s) which looks for either the beginning of the string or a space/tab/line break that’s next to a character that’s not a space/tab/line-break (\S), then returns all matches /g in the string.
Falsy Bouncer
I was able to refactor my first attempts into the following which uses filter():
function bouncer(arr) {
return arr.filter(item => item);
}
According to the Falsy Bouncer fCC Guide, it’s possible to use the Boolean function within filter() like this:
function bouncer(arr) {
return arr.filter(Boolean);
}
This is a good reminder that built-in functions can be used within map(), reduce(), and filter() functions, not just functions created at the moment (i.e. anonymous functions).
Thanks everyone for looking over my and other’s code and sharing your own code. I’ve learned a lot from you all so far and I’m really grateful for this forum and the fCC community in general. 