This is part 3 of a series in which I give solutions to the Free Code Camp Algorithmic challenges. Have a look at part 1 here and part 2 here. You can also look at the github repo with all my solutions here.
Don't look at this post until you've solved these challenges yourself! You've been warned. :)
Ok, with all that out of the way, Let's get on to the next challenges. :)
In this challenge I want to take any sentence, capitalize the first letter of each word and make all other letters lower case.
Here's the function that does that:
const R = require('ramda') const f = R.pipe( R.split(' '), R.map( R.pipe( R.split(''), R.map(R.toLower), R.adjust(R.toUpper, 0), R.join(''))), R.join(' '))
R, like always, is for ramda and
R.pipe gets us a function built out of a pipeline of functions.
First thing that happens is we split up our sentence into an array of words and map on that array. Each word gets split into an array of characters. We set each letter to lower case with another map, then adjust the first character to be upper case.
Lastly we join words, then the whole sentence back up.
Ok! Next one!
Here we're given an array of arrays of numbers. Our task is to return an array of numbers, each of which is the largest in each number array.
This one is a one-liner:
const f = R.map(R.pipe(R.sort((x, y) => y - x), R.head))
We map over the array. For each array in the array, we sort it in descending order and return its head.
Ok, here comes the next one. :)
Here we're asked to create a function that takes two strings. The second string should match the ending of the first string.
It's another one-liner:
const f = (str, target) => (new RegExp(target + '$')).test(str)
So, I just realized I've never posted about regular expressions on this blog! That's coming up soon!
Briefly, a regular expression is a pattern you can use to match against a string and get a
false depending on whether you get a match or not or you can get a substring or array of substrings that match the pattern.
We create a new
target + '$'. So if our first argument is
'potato' and our second argument is
'ato' the string
'potato' will be tested against the pattern
ato$, where the
$ symbol means the end of the string.
'potato' matches the pattern
'potatoes' does not.
Again, more on this in another post.
Happy coding! :)