Created
June 23, 2019 17:42
-
-
Save alecchampaign/0b4d1e1c9240517cef5aa83c30f59f1e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Numbers pipeline | |
| const nums = [10, 20, 30, 40]; // Array of numbers | |
| let addNums = nums => nums.reduce((acc, x) => acc + x); // Adds all numbers in an array together | |
| let divideByTwo = number => number / 2; | |
| // Function to be used as callback in reduce. Will pass function a as an argument (callback) in function b (higher order function). | |
| let _pipe = (a,b) => arg => b(a(arg)) | |
| // Reduces a potentially infinite number of operations using the above '_pipe' function. | |
| // This allows two function at a time, one as a callback to the other (higher order) function. The result of which is then | |
| // passed as a callback to the next function to be reduced. | |
| let pipe = (...ops) => ops.reduce(_pipe); | |
| // Returns a function which awaits an argument (the 'arg' parameter in the '_pipe' function. | |
| let addDivide = pipe(addNums, divideByTwo); | |
| console.log(addDivide(nums)); | |
| // Prints 50 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment