- Unary function: (input) => output
- Hight order function: (a) => (b) => c
//before
const handleSumbit = async formValues => {
const values = await validate(formValues)
const actualValues = await transform(values)
const result = await post(acutalValues)
return result
}
//after
const handleSumbitFp = asyncFlow(validate, transform, post)
flow
accept functions, return a functionUsage 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') // result = 3
pipe
fisrt param is a value, rest params are functionsUsage 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)) // result = 3
compose
The reverse version offlow
, 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 byFlow = flow(isEmpty, not, filter)
// const normal = (x)=>filter(not(isEmpty(x)))
const fp = compose(filter, not, isEmpty)
const getLength = (x: string) => x.length
const increase = (x: number) => x + 1
const fn = compose(increase, getLength) // fn = (x:string)=>number
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())
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
waitAll
= Promise.all()
toList
= Array.from()
unique
= new Set()
pickFn
| omitFn
| groupByFn
| separeByFn
const validate = () => {
throw new Error('invalidate')
}
const post = async data => axios.post('/api', data)
const submit = flow(validate, post)
submit({}).catch(e => {
//never reach, because `validate` is not async function
})