Guest User

Untitled

a guest
May 26th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.19 KB | None | 0 0
  1. # Functional Programming Cheat Sheet
  2.  
  3. ## Arrow Functions (Fat Arrows)
  4.  
  5. Arrow functions create a concise expression that encapsulates a small piece of functionality. Additionally,
  6. arrows retain the scope of the caller inside the function eliminating the need of self = this.
  7.  
  8. ### Example
  9.  
  10. // const multiply = function(x,y) {
  11. // return x * y;
  12. // }
  13. // Can be rewritten as:
  14. // const multiply = (x, y) => { return x * y };
  15. // Since the function is a single expression return and braces are not
  16. // needed.
  17. const multiply = (x, y) => x * y;
  18. console.log(multiply(5,10)) //50
  19.  
  20. ## Function Delegates
  21.  
  22. Function delegates encapsulate a method allowing functions to be composed or passed as data.
  23. Example
  24.  
  25. const isZero = n => n === 0;
  26. const a = [0,1,0,3,4,0];
  27. console.log(a.filter(isZero).length); // 3
  28.  
  29. ## Expressions Instead of Statements
  30.  
  31. Statements define an action and are executed for their side effect. Expressions produce a result without
  32. mutating state.
  33.  
  34. ### Statement
  35.  
  36. const getSalutation = function(hour) {
  37. var salutation; // temp value
  38. if (hour < 12) {
  39. salutation = "Good Morning";
  40. } else {
  41. salutation = "Good Afternoon";
  42. }
  43. return salutation; // mutated value
  44. };
  45.  
  46.  
  47. ### Expression
  48.  
  49. const getSalutation = hour => (hour < 12 ? "Good Morning" : "Good Afternoon");
  50.  
  51. console.log(getSalutation(10)); // Good Morning
  52.  
  53.  
  54. ## Higher Order Functions
  55.  
  56. A function that accepts another function as a parameter, or returns another function.
  57.  
  58. ### Example
  59.  
  60. function mapConsecutive(values, fn) {
  61. let result = [];
  62. for (let i = 0; i < values.length - 1; i++) {
  63. result.push(fn(values[i], values[i + 1]));
  64. }
  65. return result;
  66. }
  67. const letters = ["a", "b", "c", "d", "e", "f", "g"];
  68. let twoByTwo = mapConsecutive(letters, (x, y) => [x, y]);
  69. console.log(twoByTwo);
  70. // [[a,b], [b,c], [c,d], [d,e], [e,f], [f,g]]
  71.  
  72.  
  73.  
  74. ## Currying
  75.  
  76. Currying allows a function with multiple arguments to be translated into a sequence of functions. Curried
  77. functions can be tailored to match the signature of another function.
  78.  
  79. ### Example
  80.  
  81. const convertUnits = (toUnit, factor, offset = 0) => input =>
  82. ((offset + input) * factor).toFixed(2).concat(toUnit);
  83. const milesToKm = convertUnits("km", 1.60936, 0);
  84. const poundsToKg = convertUnits("kg", 0.4546, 0);
  85. const farenheitToCelsius = convertUnits("degrees C", 0.5556, -32);
  86. milesToKm(10); //"16.09 km"
  87. poundsToKg(2.5); //"1.14 kg"
  88. farenheitToCelsius(98); //"36.67 degrees C"
  89. const weightsInPounds = [5, 15.4, 9.8, 110];
  90.  
  91. // without currying
  92. const weightsInKg = weightsInPounds.map(x => convertUnits("kg", 0.4546, 0)(x));
  93.  
  94. // with currying
  95. const weightsInKg = weightsInPounds.map(poundsToKg);
  96. // 2.27kg, 7.00kg, 4.46kg, 50.01kg
  97.  
  98. ## Array Manipulation Functions
  99.  
  100. Array Functions are the gateway to functional programming in JavaScript. These functions make short work of
  101. most imperative programming routines that work on arrays and collections.
  102.  
  103. `[].every(fn)`
  104. Checks if all elements in an array pass a test.
  105.  
  106. `[].some(fn) | [].includes(fn)`
  107. Checks if any of the elements in an array pass a test.
  108.  
  109. `[].find(fn)`
  110. Returns the value of the first element in the array that passes a test.
  111.  
  112. `[].filter(fn)`
  113. Creates an array filled with only the array elements that pass a test.
  114.  
  115. `[].map(fn)`
  116. Creates a new array with the results of a function applied to every element in the array.
  117.  
  118. `[].reduce(fn(accumulator, currentValue))`
  119. Executes a provided function for each value of the array (from left-to-right). Returns a single value, the accumulator.
  120.  
  121. `[].sort(fn(a,b))` warning, mutates state!
  122. Modifies an array by sorting the items within an array. An optional compare function can be used to customize sort
  123. behavior. Use the spread operator to avoid mutation. `[...arr].sort()`
  124.  
  125. `[].reverse()` warning, mutates state!
  126. Reverses the order of the elements in an array. Use the spread operator to avoid mutation. `[...arr].reverse()`
  127.  
  128. ## Method Chaining
  129.  
  130. Method chains allow a series of functions to operate in succession to reach a final result. Method chains allow
  131. function composition similar to a pipeline.
  132.  
  133. ### Example
  134.  
  135. let cart = [
  136. { name: "Drink", price: 3.12 },
  137. { name: "Steak", price: 45.15 },
  138. { name: "Drink", price: 11.01 }
  139. ];
  140. let drinkTotal = cart
  141. .filter(x => x.name === "Drink")
  142. .map(x => x.price)
  143. .reduce((t, v) => (t += v))
  144. .toFixed(2);
  145. console.log(`Total Drink Cost $${drinkTotal}`); // Total Drink Cost $14.13
  146.  
  147. ## Pipelines
  148.  
  149. A pipeline allows for easy function composition when performing multiple operations on a variable. Since
  150. JavaScript lacks a Pipeline operator, a design pattern can be used to accomplish the task.
  151.  
  152. ### Example
  153.  
  154. const pipe = functions => data => {
  155. return functions.reduce((value, func) => func(value), data);
  156. };
  157. let cart = [3.12, 45.15, 11.01];
  158. const addSalesTax = (total, taxRate) => total * taxRate + total;
  159. const tally = orders =>
  160. pipe([
  161. x => x.reduce((total, val) => total + val), // sum the order
  162. x => addSalesTax(x, 0.09),
  163. x => `Order Total = ${x.toFixed(2)}` // convert to text
  164. ])(orders); // Order Total = 64.62
Add Comment
Please, Sign In to add comment