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