Skip to content

Instantly share code, notes, and snippets.

@dhwang
Last active July 4, 2025 17:03
Show Gist options
  • Save dhwang/f73facf267e0ecad9afc5de69cf62c4e to your computer and use it in GitHub Desktop.
Save dhwang/f73facf267e0ecad9afc5de69cf62c4e to your computer and use it in GitHub Desktop.
chain function execution using reduce
/**
* chainFunctions() creates a function that returns the result of invoking the given list of functions with
* where each successive invocation is supplied the return value of the previous.
* @example
* const replacer = chainFunctions([replaceNewLine, replaceEntities, replaceMultiSpace]);
* const cleanStr = replacer(originalString);
* @param {Function[]} fns - list of functions to be invoked
* @returns {*} function execution result
*/
export const chainFunctions = (fns) => (input) => fns.reduce((value, fn) => fn(value), input);
@dhwang
Copy link
Author

dhwang commented Jul 4, 2025

  const replacer = chainFunctions([replaceNewLine, replaceEntities, replaceMultiSpace]);
  const cleanStr = replacer(originalString);

@dhwang
Copy link
Author

dhwang commented Jul 4, 2025

help create better abstraction when we don't want to modify String or native object, but still need to chain multiple functions and pipe result of previous operation into the next function.

[replaceNewLine, replaceEntities, replaceMultiSpace]

This looks simple but these steps done inside a large function, what's happening and why will quickly get lost.

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