You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # FP Guide
  2. **date-fns** v2.x provides [functional programming](https://en.wikipedia.org/wiki/Functional_programming) (FP)
  3. friendly functions, like those in [lodash](https://github.com/lodash/lodash/wiki/FP-Guide),
  4. that support [currying](https://en.wikipedia.org/wiki/Currying).
  5. ## Table of Contents
  6. - [Usage](#usage)
  7. - [Using Function Composition](#using-function-composition)
  8. ## Usage
  9. FP functions are provided via `'date-fns/fp'` submodule.
  10. Functions with options (`format`, `parse`, etc.) have two FP counterparts:
  11. one that has the options object as its first argument and one that hasn't.
  12. The name of the former has `WithOptions` added to the end of its name.
  13. In **date-fns'** FP functions, the order of arguments is reversed.
  14. ```javascript
  15. import { addYears, formatWithOptions } from 'date-fns/fp'
  16. import { eo } from 'date-fns/locale'
  17. import toUpper from 'lodash/fp/toUpper' // 'date-fns/fp' is compatible with 'lodash/fp'!
  18. // If FP function has not received enough arguments, it returns another function
  19. const addFiveYears = addYears(5)
  20. // Several arguments can be curried at once
  21. const dateToString = formatWithOptions({ locale: eo }, 'd MMMM yyyy')
  22. const dates = [
  23. new Date(2017, 0 /* Jan */, 1),
  24. new Date(2017, 1 /* Feb */, 11),
  25. new Date(2017, 6 /* Jul */, 2)
  26. ]
  27. const formattedDates = dates.map(addFiveYears).map(dateToString).map(toUpper)
  28. //=> ['1 JANUARO 2022', '11 FEBRUARO 2022', '2 JULIO 2022']
  29. ```
  30. ## Using Function Composition
  31. The main advantage of FP functions is support of functional-style
  32. [function composing](https://medium.com/making-internets/why-using-chain-is-a-mistake-9bc1f80d51ba).
  33. In the example above, you can compose `addFiveYears`, `dateToString` and `toUpper` into a single function:
  34. ```javascript
  35. const formattedDates = dates.map((date) => toUpper(dateToString(addFiveYears(date))))
  36. ```
  37. Or you can use `compose` function provided by [lodash](https://lodash.com) to do the same in more idiomatic way:
  38. ```javascript
  39. import compose from 'lodash/fp/compose'
  40. const formattedDates = dates.map(compose(toUpper, dateToString, addFiveYears))
  41. ```
  42. Or if you prefer natural direction of composing (as opposed to the computationally correct order),
  43. you can use lodash' `flow` instead:
  44. ```javascript
  45. import flow from 'lodash/fp/flow'
  46. const formattedDates = dates.map(flow(addFiveYears, dateToString, toUpper))
  47. ```