Functional programming and dot chaining

  • Javascript
  • FP
  • Lodash
How often do we perform a series of mutations on the same data? I don't know about you but I hate to introduce more and more state into the application via variables with more and more confusing names. It's not until you work on a codebase of a certain size that you feel the need to abstract away certain logic into neat little packages.
First, allow me to present you with some code that sanitises a comma separated list of strings and returns a shuffled array. There is nothing wrong as such with this imperative approach. I'm sure it works as expected. However, it seems like a lot of code for a fairly simple transformation of data.
function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}
function processString(str) {
  if (!str) return [];
  const stringsArray = str.split(",");
  let processedStringsArray = [];
  for (let i = 0; i < stringsArray.length; i++) {
    if (stringsArray[i] !== "") {
      processedStringsArray.push(stringsArray[i].trim());
    }
  }
  return shuffleArray(processedStringsArray);
}
const stringsArray = processString(str);
Thankfully, there is another way. Thanks to function programming and a little help from Lodash, we are actually able to reduce this by 10 lines! Firstly, the processString function can be split into smaller utility functions that can be reusable and passed around the application. Lodash provides a lot of these for you. Dot chaining then connects these functions in series and provides a nice, readable block of code that even a novice could understand.
const stringsArray = str
  ? _.chain(str)
      .split(",")
      .filter((x) => x !== "")
      .map((x) => x.trim())
      .shuffle()
      .value()
  : [];