Skip to content

Instantly share code, notes, and snippets.

@marcmartino
Created February 7, 2021 00:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcmartino/2ef6ee4307294f270b14fa1964448358 to your computer and use it in GitHub Desktop.
Save marcmartino/2ef6ee4307294f270b14fa1964448358 to your computer and use it in GitHub Desktop.
Example of an imperative vs functional approaches

Imperative v Functional

Many times introduction to functional material tends to focus on really facile aspects of functional programming like "Use map or reduce instead of a for loop". To me this doesn't do justice to what a beginner functional approach really should be.

A good example to display how different the two approaches can be would be a simple range function

Imperative

function  range(start, end, step = 1) {
  let  numBetween = [];
  const  rangeStep = start < end ? Math.abs(step) : Math.abs(step) * -1;
  const  loopCond = (i) => (start > end ? end <= i : end >= i);
  
  for (let  i = start; loopCond(i); i += rangeStep) {
    numBetween.push(i);
  }
  
  return  numBetween;
}

Functional

const range = (start, end, step = 1) => {
  const rangeLength = Math.ceil((Math.abs(start - end) + 1) / Math.abs(step));
  const stepVal = start < end ? Math.abs(step) : Math.abs(step) * -1;
  return [...new Array(rangeLength)].map(
    (_, i) => i * stepVal + start
  );
};

A decent amount can be said about either approach here but the big things I would implore the beginner to grasp is that in the imperative approach is much more of a step by step walk through of how you want the final array to be constructed value by value. The functional approach is more of a data transformation- you want an array of a certain length and the array values should follow a given pattern.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment