Free Code Camp Algorithmic Challenges Part 6

This is part 6 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 part 1, part 2, part 3, part 4, and part 5. You can also look at the github repo with all my solutions here.

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

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

Falsy Bouncer

Here we're asked to provide a function that strips all "falsey" values from an array. Values are "falsey" if JavaScript evaluates them to false.

Here-a is-a the code-a:

const  
    R = require('ramda')

module.exports = R.filter(x => x)  

Since all ramda functions are auto-curried and arranged data-last, this is all we have to do. Oh, and here's that link to filter if you've not used it before.

Seek and Destroy

So we need to make a function that takes an array as its first argument, and then any number of other arguments. We need to return a copy of the array whose elements do not include any of those other arguments.

For example, f([1, 2, 3, 4, 5], 2, 4, 5) would return [1, 3], and f(['hey', 'you', 'are', 'a', 'hamster', 'man'], 'hey', 'man') would return ['you', 'are', 'a', 'hamster'].

Codey codey:

module.exports = (xs, ...ys) =>  
    xs.filter(x => !ys.includes(x))

I talk about the ... operator here, but basically it makes xs the given array and turns the remainder of the arguments into another array, ys. Now all we do is filter out those elements in xs included in ys.

Nexty next next!

Where do I belong

We need to make a function that takes an array of numbers xs and a number y. The function needs to sort xs then figure out which index to insert y into xs that will keep the resulting array sorted.

code-o-reeno!

module.exports = (xs, y) => xs  
    .sort((a, b) => a > b)
    .filter(x => x < y)
    .length

First we sort the array, then we remove all numbers from the array greater than or equal to y, finally the length of the resulting array will be the same as the index we needed to insert y into xs at (e.g. one index more than the last index of the filtered array).

Ok, that's it for now. See you next week!

Looking for a software developer?