Skip to content

Instantly share code, notes, and snippets.

@dodie
Last active November 26, 2016 08:50
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 dodie/2ccf275d732518249599f0621a822ae0 to your computer and use it in GitHub Desktop.
Save dodie/2ccf275d732518249599f0621a822ae0 to your computer and use it in GitHub Desktop.

Example where functional style can simplify our lives.

Source: Dr. Venkat Subramaniam - Functional Programming with Java 8 (https://www.youtube.com/watch?v=Ee5t_EGjv0A)

Goal: calculate the double of the first even number greater than 3

var numbers = [1,2,3,4,5,6,7,8,9,10];

Imperative approach:

var result = 0;
for(var i = 0; i < numbers.length; i++) {
  var e = numbers[i];
  if (e > 3 && e % 2 == 0) {
    result = e * 2;
    break;
  }
}
console.log(result);

Functional approach:

const result = numbers.filter((n) => n % 2 === 0)
                      .filter((n) => n > 3)
                      .map((n) => n * 2)[0];
console.log(result);

Making it more self-documenting, by defining more functions:

const isEven = (n) => n % 2 === 0;
const isGreaterThan = (x) => (n) => n > x;
const double = (n) => n * 2;

const result = numbers.filter(isEven)
                      .filter(isGreaterThan(3))
                      .map(double)[0];
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment