Currying
柯里化把一个多参数函数拆成多层单参数函数,让函数更容易复用和组合。以下为 src/currying.ts 中每个导出函数各一例(仅类型的导出略)。
项目中的实现
- 源码:
src/currying.ts
各函数示例
logger
import { logger } from 'wssf-kage-js';
const log = logger('dev')('INFO');
log('服务已启动');
request
import { request } from 'wssf-kage-js';
const getJson = request('https://api.example.com')({ Accept: 'application/json' })('/v1/items');
void getJson({ page: 1, size: 10 });
eventHandler
import { eventHandler } from 'wssf-kage-js';
const onClick = eventHandler<MouseEvent>('sidebar');
validate
import { validate } from 'wssf-kage-js';
const checkId = validate(/^\d{6}$/)('须为 6 位数字');
checkId('123456'); // => { pass: true }
isMobile
import { isMobile } from 'wssf-kage-js';
isMobile('13800138000'); // => { pass: true }
isEmail
import { isEmail } from 'wssf-kage-js';
isEmail('bad'); // => { pass: false, tip: '邮箱格式错误' }
convertCurrency
import { convertCurrency } from 'wssf-kage-js';
convertCurrency(0.14)(100); // => '14.00'
createCls
import { createCls } from 'wssf-kage-js';
createCls('ui')(true)('button');
filterBy
import { filterBy } from 'wssf-kage-js';
type Row = { tags: string[]; name: string };
filterBy<Row>('tags')('a')({ tags: ['a', 'b'], name: 'x' }); // => true
promptFactory
import { promptFactory } from 'wssf-kage-js';
promptFactory('助手')('用户正在写文档')('帮我列提纲');
curry
import { curry } from 'wssf-kage-js';
const add = (a: number, b: number, c: number) => a + b + c;
curry(add)(1)(2)(3); // => 6
compose
import { compose, toLowerCase } from 'wssf-kage-js';
compose<string>(toLowerCase, (s) => s.trim())(' HELLO ');
pipe
import { pipe, toUpperCase } from 'wssf-kage-js';
pipe<string>((s) => s.trim(), toUpperCase)(' hi ');
get
import { get } from 'wssf-kage-js';
get({ user: { name: 'Ada' } })('user.name')();
set
import { set } from 'wssf-kage-js';
const o = { a: { b: 1 } };
set(o)('a.c')(2);
map
import { map } from 'wssf-kage-js';
map((n: number) => n * 2)([1, 2, 3]);
filter
import { filter } from 'wssf-kage-js';
filter((n: number) => n > 1)([1, 2, 3]);
reduce
import { reduce } from 'wssf-kage-js';
reduce((acc: number, n: number) => acc + n)(0)([1, 2, 3]);
add
import { add } from 'wssf-kage-js';
add(2)(3); // => 5
multiply
import { multiply } from 'wssf-kage-js';
multiply(2)(4); // => 8
divide
import { divide } from 'wssf-kage-js';
divide(10)(2); // => 5
subtract
import { subtract } from 'wssf-kage-js';
subtract(10)(3); // => 7
split
import { split } from 'wssf-kage-js';
split(',')('a,b,c');
join
import { join } from 'wssf-kage-js';
join('-')(['x', 'y']);
toUpperCase
import { toUpperCase } from 'wssf-kage-js';
toUpperCase('ab');
toLowerCase
import { toLowerCase } from 'wssf-kage-js';
toLowerCase('AB');
debounce
import { debounce } from 'wssf-kage-js';
debounce(200)((x: number) => console.log(x));
throttle
import { throttle } from 'wssf-kage-js';
throttle(200)((x: number) => console.log(x));
适合的场景
- 固定部分配置后返回专用函数
- 构建请求器、校验器、日志器
- 与组合/管道一起做数据流水线