UNPKG

2.36 kBMarkdownView Raw
1# FP Guide
2
3**date-fns** v2.x provides [functional programming](https://en.wikipedia.org/wiki/Functional_programming) (FP)
4friendly functions, like those in [lodash](https://github.com/lodash/lodash/wiki/FP-Guide),
5that 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
15FP functions are provided via `'date-fns/fp'` submodule.
16
17Functions with options (`format`, `parse`, etc.) have two FP counterparts:
18one that has the options object as its first argument and one that hasn't.
19The name of the former has `WithOptions` added to the end of its name.
20
21In **date-fns'** FP functions, the order of arguments is reversed.
22
23```javascript
24import { addYears, formatWithOptions } from 'date-fns/fp'
25import { eo } from 'date-fns/locale'
26import 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
29const addFiveYears = addYears(5)
30
31// Several arguments can be curried at once
32const dateToString = formatWithOptions({ locale: eo }, 'd MMMM yyyy')
33
34const dates = [
35 new Date(2017, 0 /* Jan */, 1),
36 new Date(2017, 1 /* Feb */, 11),
37 new Date(2017, 6 /* Jul */, 2)
38]
39
40const 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
46The 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
49In the example above, you can compose `addFiveYears`, `dateToString` and `toUpper` into a single function:
50
51```javascript
52const formattedDates = dates.map((date) => toUpper(dateToString(addFiveYears(date))))
53```
54
55Or you can use `compose` function provided by [lodash](https://lodash.com) to do the same in more idiomatic way:
56
57```javascript
58import compose from 'lodash/fp/compose'
59
60const formattedDates = dates.map(compose(toUpper, dateToString, addFiveYears))
61```
62
63Or if you prefer natural direction of composing (as opposed to the computationally correct order),
64you can use lodash' `flow` instead:
65
66```javascript
67import flow from 'lodash/fp/flow'
68
69const formattedDates = dates.map(flow(addFiveYears, dateToString, toUpper))
70```
\No newline at end of file