concept shortcut fusion in category functional programming

appears as: shortcut fusion
Functional Programming in JavaScript

This is an excerpt from Manning's book Functional Programming in JavaScript.

  • Using shortcut fusion in functional libraries
  • This declarative mode of programming means you don’t have to worry about how the functions work, just what needs to be done, by defining what it is you want to accomplish ahead of time. On some occasions, this allows Lodash to internally optimize the execution of your program using shortcut fusion. It’s a function-level optimization that can merge the execution of some functions into one and condense the number of internal data structures used to compute intermediate results. Creating fewer data structures lowers the excess memory needed when processing large collections.

    Listing 7.1. Lodash’s lazy evaluation and shortcut fusion
    const square = (x) => Math.pow(x, 2);
    const isEven = (x) => x % 2 === 0;
    const numbers = _.range(200);                          #1
    const result = 
       _.chain(numbers)    
        .map(square)
        .filter(isEven)
        .take(3)                                           #2
        .value();  //-> [0,4,16]
    result.length; //-> 5
    

    Listing 7.1 has a couple of optimizations: First, the call to take(3) advises Lodash to only worry about the first three values that pass the mapping and filtering criteria instead of wasting precious cycles on the remaining 195 elements. Second, shortcut fusion allows the subsequent calls to map and filter to fuse into compose(filter(isEven), map(square)). You can easily proof this by augmenting the square and isEven functions with trace logs (using Ramda to effectively compose the tap combinator for logging purposes):