Search code examples
javascriptmethodschaining

Extract a method chain in Javascript?


Given a function which performs a set of operations

const addSum = arr => arr.map(i => i+1).filter(i => i % 2 !== 0).map(i => i+1)

Is there a way to extract the method chain? For example, get a tree of the operations performed in an object like

{map: {filter: "map"}}

Edit: Updated example


Solution

  • You could save the name of the extension methods and the callback in a 2D array. Then use reduce to call each function one by one and return the result as accumulator in each iteration

    const sequence = (initial, ops) => ops.reduce((acc, [f, cb]) => acc[f](cb), initial)
    
    // Save each opeartion in: ["extension name", callback] format
    const operations = [
      ['map', i => i + 1],
      ['filter', i => i % 2],
      ['map', i => i + 2]
    ]
    
    const output = sequence([1, 2, 3], operations)
    
    console.log(output)

    Or, you could use a pipe function used in functional pattern

    const increment = n => arr => arr.map(i => i + n)
    const evenFilter = arr => arr.filter(i => i % 2)
    
    function pipe(...fns) {
      return arg => fns.reduce((prev, fn) => fn(prev), arg);
    }
    
    console.log(
      pipe(increment(1), evenFilter, increment(2))([1, 2, 3])
    )