This is part 5 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. :)
Ok, with all that out of the way, Let's get on to the next challenges. :)
This one asks us to split an array into some number of chunks of size n, and put that into an array. For example
[1, 2, 3, 4, 5] split into chunks of size 2 is
[[1, 2], [3, 4], ].
Here's the code:
const R = require('ramda') module.exports = (xs, n) => xs.reduce((xs, x) => R.last(xs).length < n ? R.pipe( R.last, R.append(x), R.append(R.__, R.init(xs))) (xs) : R.append([x], xs), [])
It's your basic reduce call. We use it to build an array of arrays.
xs in the reducer is our accumulator (initialized as an array holding a single empty array), and
x is an element from the original array.
The reducer first checks to see if the last element of
xs is of size
n. If not we add an element to the last array in
xs. If so we add a new empty array to the end of
This one just wants us to chop the front n elements from an array, which is what slice does:
module.exports = (xs, n) => xs.slice(n)
'Nuff said. Next!
Here we're asked to write a function that takes an array of two strings. The function should return true if all the characters in the second string are contained in the first string, ignoring case.
For example, given
[[abcdefg], [CBa]] our function would return true, and for
[[sdgid], [abc]] it would return false.
Code code code:
module.exports = arr => R.pipe( R.split(''), R.all(c => arr.match(new RegExp(c, 'i')))) (arr)
First we split up
arr into a character array.
R.all maps over each element of the array and then returns true if all elements in the resulting array are true. It's a shorthand for mapping a function on the array and then anding all the elements of the array returned by map.
Here we check to see if
arr matches the pattern
new RegExp(c, 'i') which is just the character
c ignoring case. Which is the same thing as saying that we check if
c is in
arr (ignoring case).
More on regular expressions in another post.
Ok, that's enough for one post. Happy coding!