Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. var _ = require('lodash');
  2.  
  3. class Formatter{
  4. constructor(repetitions){
  5. this.repetitions = repetitions;
  6. }
  7.  
  8. format1(txt){
  9. return `${"[" .repeat(this.repetitions)} ${txt} ${"]" .repeat(this.repetitions)}`;
  10. }
  11.  
  12. format2(txt){
  13. return `${"(" .repeat(this.repetitions)} ${txt} ${")" .repeat(this.repetitions)}`;
  14. }
  15. }
  16.  
  17. let cities = [
  18. "Paris",
  19. null,
  20. "Toulouse",
  21. "Xixon",
  22. "",
  23. "Berlin"
  24. ];
  25.  
  26. let result = _.reverse(
  27. _.take(
  28. _.compact(cities)
  29. , 3
  30. )
  31. );
  32.  
  33. console.log(result);
  34. console.log("------------------");
  35.  
  36. result = _.flow([
  37. _.compact,
  38. (ar) => _.take(ar, 3),
  39. _.reverse
  40. ])(cities);
  41.  
  42. console.log(result);
  43. console.log("------------------");
  44.  
  45. result = _.chain(cities)
  46. .compact()
  47. .take(3)
  48. .reverse()
  49. .value();
  50.  
  51. console.log(result);
  52. console.log("------------------");
  53.  
  54. //when composing methods, we'll need to provide the right "this" value
  55. let formatter = new Formatter(2);
  56.  
  57. //here we're missing the "this"
  58. let formatFn = _.flow([
  59. formatter.format1,
  60. formatter.format2
  61. ]);
  62.  
  63. console.log(formatFn("hi"));
  64. // hi
  65. console.log("------------------");
  66.  
  67. //_.flow will pass as "this" to each function the "this" bound to the created function, so let's do a bind:
  68. let boundFormatFn = formatFn.bind(formatter);
  69. console.log(boundFormatFn("hi"));
  70. // (( [[ hi ]] ))
  71. console.log("------------------");
  72.  
  73. //if _.flow were not providing that feature, we could create wrapping functions for each method call
  74. let formatFn2 = _.flow([
  75. (st) => formatter.format1(st),
  76. (st) => formatter.format2(st)
  77. ]);
  78. console.log(formatFn2("hi"));
  79. //(( [[ hi ]] ))
  80. console.log("------------------");
  81.  
  82. //or call bind in each method-function being composed:
  83. let formatFn3 = _.flow([
  84. formatter.format1.bind(formatter),
  85. formatter.format2.bind(formatter)
  86. ]);
  87. console.log(formatFn3("hi"));
  88. //(( [[ hi ]] ))
  89. console.log("------------------");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement