SHARE
TWEET

Untitled

a guest Sep 12th, 2019 92 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Helper functions
  2.  
  3. const compose = (...fns) => x =>
  4.   fns.reduceRight((y, f) => f(y), x)
  5.  
  6. const curry = (fn, n) => {  
  7.   const arity = n || fn.length  
  8.   return (...params) =>
  9.     params.length >= arity    
  10.       ? fn(...params)    
  11.       : curry(
  12.           (...rest) => fn(...params, ...rest),
  13.           arity - params.length
  14.         )
  15. }
  16.  
  17. const log = curry((label, value) => {
  18.   console.log(`[${label}]`, value)
  19.   return value
  20. })
  21.  
  22. const prop = curry((name, obj) =>
  23.   obj[name]
  24. )
  25.  
  26. // Array functions
  27.  
  28. const map = curry((mapper, list) =>
  29.   list.map(mapper)
  30. )
  31.  
  32. const filter = curry((predicate, list) =>
  33.   list.filter(predicate)
  34. )
  35.  
  36. const reduce = curry((reducer, initial, list) =>
  37.   list.reduce(reducer, initial)
  38. )
  39.  
  40. // Domain functions
  41.  
  42. const add = curry((x, y) =>
  43.   x + y
  44. )
  45.  
  46. const isAdmin = prop('admin')
  47.  
  48. const getAge = prop('age')
  49.  
  50. const sum = reduce(add, 0)
  51.  
  52. const sumAdminAges = compose(
  53.   sum,
  54.   log('Ages'),
  55.   map(getAge),
  56.   log('Admin users'),
  57.   filter(isAdmin),
  58.   log('List of users')
  59. )
  60.  
  61. // execution
  62.  
  63. const users = [
  64.   { admin: true, age: 30 },
  65.   { admin: false, age: 45 },
  66.   { admin: true, age: 40 },
  67.   { admin: false, age: 80 },
  68. ]
  69.  
  70. sumAdminAges(users)
  71.  
  72. // [List of users] [ { admin: true, age: 30 },
  73. //   { admin: false, age: 45 },
  74. //   { admin: true, age: 40 },
  75. //   { admin: false, age: 80 } ]
  76. // [Admin users] [ { admin: true, age: 30 }, { admin: true, age: 40 } ]
  77. // [Ages] [ 30, 40 ]
  78. // 70
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top