fp-pipe-ref

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

pipe & flow Quick Reference

pipe & flow 快速参考指南

pipe - Transform a Value

pipe - 转换单个值

typescript
import { pipe } from 'fp-ts/function'

// pipe(startValue, fn1, fn2, fn3)
// = fn3(fn2(fn1(startValue)))

const result = pipe(
  '  hello world  ',
  s => s.trim(),
  s => s.toUpperCase(),
  s => s.split(' ')
)
// ['HELLO', 'WORLD']
typescript
import { pipe } from 'fp-ts/function'

// pipe(初始值, 函数1, 函数2, 函数3)
// 等价于 fn3(fn2(fn1(初始值)))

const result = pipe(
  '  hello world  ',
  s => s.trim(),
  s => s.toUpperCase(),
  s => s.split(' ')
)
// ['HELLO', 'WORLD']

flow - Create Reusable Pipeline

flow - 创建可复用的管道

typescript
import { flow } from 'fp-ts/function'

// flow(fn1, fn2, fn3) returns a new function
const process = flow(
  (s: string) => s.trim(),
  s => s.toUpperCase(),
  s => s.split(' ')
)

process('  hello world  ') // ['HELLO', 'WORLD']
process('  foo bar  ')     // ['FOO', 'BAR']
typescript
import { flow } from 'fp-ts/function'

// flow(函数1, 函数2, 函数3) 返回一个新函数
const process = flow(
  (s: string) => s.trim(),
  s => s.toUpperCase(),
  s => s.split(' ')
)

process('  hello world  ') // ['HELLO', 'WORLD']
process('  foo bar  ')     // ['FOO', 'BAR']

When to Use

适用场景

UseWhen
pipe
Transform a specific value now
flow
Create reusable transformation
使用API适用时机
pipe
立即转换特定值
flow
创建可复用的转换逻辑

With fp-ts Types

结合fp-ts类型使用

typescript
import * as O from 'fp-ts/Option'
import * as A from 'fp-ts/Array'

// Option chain
pipe(
  O.fromNullable(user),
  O.map(u => u.email),
  O.getOrElse(() => 'no email')
)

// Array chain
pipe(
  users,
  A.filter(u => u.active),
  A.map(u => u.name)
)
typescript
import * as O from 'fp-ts/Option'
import * as A from 'fp-ts/Array'

// Option链式调用
pipe(
  O.fromNullable(user),
  O.map(u => u.email),
  O.getOrElse(() => 'no email')
)

// Array链式调用
pipe(
  users,
  A.filter(u => u.active),
  A.map(u => u.name)
)

Common Pattern

常见模式

typescript
// Data last enables partial application
const getActiveNames = flow(
  A.filter((u: User) => u.active),
  A.map(u => u.name)
)

// Reuse anywhere
getActiveNames(users1)
getActiveNames(users2)
typescript
// 数据后置支持部分应用
const getActiveNames = flow(
  A.filter((u: User) => u.active),
  A.map(u => u.name)
)

// 在任意地方复用
getActiveNames(users1)
getActiveNames(users2)