Ultra small code using Functional Programming

Yoganathan Palaniswamy
5 min readMay 30, 2020
Photo by Pankaj Patel on Unsplash

Let me begin by saying that this read is not for the lightest of hearts. It contains a lot of Javascript nuances (like map, reduce), which if you don’t know in detail can leave you wondering. I try to explain briefly about them, but I’ll also provide links that will explain them in detail.

Introduction

I have this weird craving for writing super short code, like writing entire functions in a single line. I do not recommend doing it that way, code readability is many times more important than your code being small in size. But I do it sometimes as a fun activity, just to check if I can do something.

So a friend approached me with a problem called the “step number problem” where you take a number and return true if all the digits differ from the neighbour by 1, either positive or negative.

545678 -> True45654  -> True12345  -> True13573  -> False12145  -> False

I remember doing this a few years ago in C, but now I wanted to try to do with as little code as possible, in JavaScript. Also, now there is a shift in the way I think and work out, compared to back then. I tend to use more functional programming syntax. Believe me, functional programming syntax (map, reduce and other higher order functions) make your code much much better, to understand and also to debug. If you aren’t using them, you must at least consider.

Important note: In my score for shortness, I take into account the number of tokens used and not the actual number of characters. Therefore according to my standard, using a variable n instead of variable number doesn’t make it any shorter.

Step 1: Split digits

There are mathematical ways to do this, for example, by taking repeated %10, till the number is > 0. But I went for the convert to string and split approach. I don’t see big performance impacts.

Step 1.1: Convert number to string

There are few ways to do this…

1. number.toString()2. String(number)3. number + ""
Yoganathan Palaniswamy

Coder, content creator. Admin of @baby_wolf_codes