Mar 28 2020

Name that Algorithm: #1

The veterans in the software industry recognize code as a liability. Code is not an asset! Maintaining 10 lines of code is easier than maintaining 100 lines of code. Similarly, 100 lines of code is easier to maintain than 1000. By reducing the size of the code, we can squeeze bugs out of their hiding place.

Consider a massive function with a reduce buried in the middle.

import _ from 'lodash';

export const getSomeValue = () => {
  // some code ...

  const highestRank = _.reduce(ranks, (acc, e) => {
    if (e.rank > acc.rank) {
      return e;
    }
    return acc;
  }, ranks[0]);

  // some more code ...
}

Have you ever seen a big function with a random reduce inside? I’m sure we all have. In fact, I am guilty of writing this time and time again. It is easy to “just crank it out” when feeling rushed.

Time to clean it up! For starters, name the function so that it is more descriptive. This is a good first step before improving on the implementation.

import _ from 'lodash';

export const getHighestRank = (ranks) => {
  return _.reduce(ranks, (acc, e) => {
    if (e.rank > acc.rank) {
      return e;
    }
    return acc;
  }, ranks[0]);
}

// export const getSomeValue...

Try thinking about by yourself for a minute. Scroll down when you are ready for the answer!

With the algorithm isolated, let us find a better implementation. One red flag in the above code is that the reduce is doing a fairly trivial task.

Lodash is quite a supercharged library. It has a lot of common operations. There has got to be a better function that we can use. The operation fetches the object with the highest rank.

import _ from 'lodash';

export const getHighestRank = (ranks) => _.maxBy(ranks, 'rank')

// export const getSomeValue...

Tada! Lodash maxBy solves the problem in one line.

If you carefully download Lodash you have every reason to learn the ins and outs of what it offers. Lodash is a great tool for 90% of data processing.