Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. const reduce = (reducer, initial, arr) => {
  2. let acc = initial;
  3. for (let i = 0, { length } = arr; i < length; i++) {
  4. acc = reducer(acc, arr[i]);
  5. }
  6. return acc;
  7. };
  8.  
  9. const addAll = nums => reducer((acc, curr) => acc + curr, 0, nums);
  10. console.log(addAll([1, 2, 3, 4, 5, 6, 7, 8, 9]));
  11.  
  12. const filter = (fn, arr) =>
  13. reduce((acc, curr) => (fn(curr) ? acc.concat([curr]) : acc), [], arr);
  14.  
  15. const over5 = nums => filter(num => num > 5, nums);
  16. console.log(over5([1, 2, 3, 4, 5, 6, 7, 8, 9]));
  17.  
  18. const compose = (...fns) => x => fns.reduceRight((y, f) => f(y), x);
  19. const trace = label => value => {
  20. console.log(`${label}: ${value}`);
  21. return value;
  22. };
  23. const g = n => n + 1;
  24. const f = n => n * 2;
  25. const h = compose(
  26. trace('after f'),
  27. f,
  28. trace('after g'),
  29. g
  30. );
  31. h(20);
  32.  
  33. const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
  34. const j = pipe(
  35. g,
  36. trace('after g'),
  37. f,
  38. trace('after f')
  39. );
  40.  
  41. const map = fn => mappable => mappable.map(fn);
  42. const arr = [1, 2, 3, 4];
  43. const isEven = n => n % 2 === 0;
  44. const stripe = n => (isEven(n) ? 'dark' : 'light');
  45. const stripeAll = map(stripe);
  46. const striped = stripeAll(arr);
  47. console.log(striped);
  48.  
  49. const flip = fn => a => b => fn(b)(a);
  50. const traceFlip = value => label => {
  51. console.log(`${label}: ${value}`);
  52. return value;
  53. };
  54. const flippedCorrectTrace = flip(traceFlip);
  55.  
  56. // array.reduce(
  57. // reducer: (accumulator: Any, current: Any) => Any,
  58. // initialValue: Any
  59. // ) => accumulator: Any”
  60.  
  61. const map = (fn, arr) =>
  62. arr.reduce((acc, item, index, arr) => acc.concat(fn(item, index, arr)), []);
  63.  
  64. const filter = (fn, arr) =>
  65. arr.reduce((newArr, item) => (fn(item) ? newArr.concat([item]) : newArr), []);
  66.  
  67. // “Partial applications can take as many or as few arguments a time as desired.Curried functions on the other hand always return a unary function: a function which takes one argument.
  68. // All curried functions return partial applications, but not all partial applications are the result of curried functions.
  69. // The unary requirement for curried functions is an important feature.”
  70.  
  71. // Tiny, recursive autocurry
  72. const curry = (f, arr = []) => (...args) =>
  73. (a => (a.length === f.length ? f(...a) : curry(f, a)))([...arr, ...args]);
  74.  
  75. const add3 = curry((a, b, c) => a + b + c);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement