This libary is focus on easy to use, only requierd you know a few concect below:
- Unary function: (input) => output
- Hight order function: (a) => (b) => c
Use Case
const handleSumbit = async formValues => {
const values = await validate(formValues)
const actualValues = await transform(values)
const result = await post(acutalValues)
return result
}
const handleSumbitFp = asyncFlow(validate, transform, post)
Begin composition
flow
accept functions, return a function
Usage scenario:
when you have a series of functions only require the return value of the previous function
const getLength = (x: string) => x.length
const increase = (x: number) => x + 1
const workFlow = flow(getLength, increase)
const result = workFlow('FP')
pipe
fisrt param is a value, rest params are functions
Usage scenario:
Distribution dependencies
const getLength = (x: string) => x.length
const increaseWith = (y: number) => (x: number) => x + y
const result = (input: string, step: number) =>
pipe('FP', getLength, increaseWith(step))
compose
The reverse version of flow
, some times it made more readable
import { compose, filter, isEmpty } from 'fp-lite'
const not =
<T>(x: T) =>
(fn: (x: T) => boolean) =>
!fn(x)
const fp = compose(filter, not, isEmpty)
const getLength = (x: string) => x.length
const increase = (x: number) => x + 1
const fn = compose(increase, getLength)
asyncFlow
accept async functions, return an async funtion
const workFlow = asyncFlow(fetch, r => r.json(), console.log)
workFlow('http://xx.json')
asyncPipe
The first param is a Promise, rest params are async functions
const result = await asyncPipe(fetch('http://xx.json'), r => r.json())
Functions work with composition function
Example
const datas = [
{ kind: 'frontend', lib: 'React' },
{ kind: 'backend', lib: 'Express' },
]
const result = pipe(
datas,
groupBy(v => v.kind),
g => g.values(),
toList,
flat,
map(v => v.lib)
)
-
Array functions (frequently used)
map
| filter
| flat
| concat
| unique
| last
| first
-
Functions for Object
pick
| omit
-
Function for grouping
groupBy
| separeBy
-
Functions for condition
maybe
| fallback
| notNull
| isEmpty
| isZero
-
Other functions
peek
|invoke
Some Functions are just alias
waitAll
= Promise.all()
toList
= Array.from()
unique
= new Set()
Normal Functions
pickFn
| omitFn
| groupByFn
| separeByFn
Not recommended for use in non typescript projects
Pitfall
const validate = () => {
throw new Error('invalidate')
}
const post = async data => axios.post('/api', data)
const submit = flow(validate, post)
submit({}).catch(e => {
})