Free Code Camp Algorithmic Challenges Part 11

This is part 11 of a series in which I give solutions to the Free Code Camp Algorithmic Challenges. Don't look at this post until you've solved these challenges yourself! You've been warned. :)

Here are the links for parts 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10. You can also look at the github repo with all my solutions.

I'm also using whatever libraries I feel like using (ramda and FolkTale in this post) and any new JavaScript features I like for all of these challenges, something you can't do at freecodecamp.com.

With all that out of the way, Let's get on to the next challenges. :)

Boo who

This one is super easy. Return true if the given argument is a boolean, false otherwise:

module.exports =  
    x => typeof x === 'boolean'

'nuff said.

Sorted Union

Here, we're asked to write a function that takes any number of arguments, each an array. It joins all these arrays and filters out any duplicates.

Here is the code for you, you hoopy frood.

const  
    R = require('ramda')

module.exports = (...xs) =>  
    R.pipe(
        R.chain(x => x),
        R.reduce(
            (ys, x) =>
                ys.includes(x)
                ? ys
                : R.append(x, ys),
            []),
        R.sort(R.subtract))
            (xs)

First we take advantage of some destructuring and turn all arguments into an array of arrays.

We use R.chain and the identity function to flatten our new array. R.chain maps, then unboxes. So, for example, if we have some array [1, 2, 3, 4] and some function f = x => [x], then [1, 2, 3, 4].map(f).map(x => x[0]) is the same as R.chain(f, [1, 2, 3, 4]).

Next we do a R.reduce call on the resulting array to create a new array with only unique values.

Lastly, we sort the array and return it.

Convert HTML Entities

When you're writing HTML there are certain reserved characters, like <, and > which don't render in an HTML document. If you want to display these in your document you can use what are called HTML entities. These are codes that your browser will convert into the reserved character when your page displays.

The function we have to write needs us to convert &, ", ', <, and > to their html entity codes: &amp;, &quot;, &apos;, &lt;, and &gt; respectively.

Here is some code for you!

module.exports = str => str  
    .replace(/&/g, '&amp;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')

Pretty easy to understand right? The only thing that might throw you for a loop is that I'm surrounding each character to be replaced with slashes and the letter g.

The slashes mean that this is a regular expression, the g means that we're not just replacing one instance of the character in the string, but all instances.

Ok, that should do it! Cya next time. :)

Looking for a software developer?