October 28, 2016
Functional Programming in ES6
Since I migrated one of the bigger projects at work to ES6, I’ve been more and more interested in functional programming and the idea of having little to no state mutation.
One of the ways that I’ve been improving my understading and skills recently has been with CodeWars. Free code kata are a great way to challenge yourself with new problems and creative solutions. Since the problems presented on CodeWars are designed by the community, I’ve seen unique solutions to problems that I never would have dreamed of.
For example I saw one particular problem solved in 1 line of code with a reverse lookup RegEx. While it wasn’t entirely practical since you would have to explain how it worked to almost everyone else on the team, it was exciting to see such a creative solution.
Here’s one example of a recent problem I solved:
Convert number to reversed array of digits
Given a random number, You have to return the digits of this number within an array in reverse order. example: 348597 -> [7,9,5,8,4,3]
And my solution could look like this (there are shorter methods, but this is the one I wrote):
const digitize = n => n.toString().split('').reverse().map(s => parseInt(s));
No variables are created, no existing data is mutated. It operates like a coin machine, data in, data out.
Here’s another problem:
Given a string, you have to return a string in which each character (case-sensitive) is repeated once. example: doubleChar("String") ==> "SSttrriinngg"
And my solution:
const doubleChar = str => str.split('').map((t) => t+t).join('');
Simple and easy to understand.
If you haven’t given it a try, I highly recommend CodeWars as a place to improve your skills and see new ways to solve old problems.
My name is Trevor Atlas – I'm a Software Developer and Designer based in Washington, DC
For the past 5 years, I've worked at agencies and startups building functional and intuitive interfaces, flexible and robust services and powerful mobile applications.
When I'm not building user interfaces in React, most of my day-to-day work involves microservices in AWS using Terraform to scaffold infrastructure, Typescript and Go for application logic and Postgres/Redis as a data store. I've also been working on mobile applications with React Native and Expo.