Cheat Sheet速查表
跳转到主要内容

101 速查表

本文根据 Devhints / 101 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2017-09-21。

101 是一个用于以函数式风格处理不可变数据的 JavaScript 库。

用法

const isObject = require('101/isObject')
isObject({}) // → true

每个函数都以模块的形式对外提供。

参见: 101

类型检查

isObject({})
isString('str')
isRegExp(/regexp/)
isBoolean(true)
isEmpty({})
isfunction(x => x)
isInteger(10)
isNumber(10.1)
instanceOf(obj, 'string')

对象

示例

let obj = {}

更新

obj = put(obj, 'user.name', 'John')
// → { user: { name: 'John' } }

读取

pluck(name, 'user.name')
// → 'John'

删除

obj = del(obj, 'user')
// → { }

获取

pluck(state, 'user.profile.name')
pick(state, ['user', 'ui'])
pick(state, /^_/)

pluck 返回具体值, pick 返回对象的子集。

参见: pluck, pick

设置

put(state, 'user.profile.name', 'john')

参见: put

删除

del(state, 'user.profile')
omit(state, ['user', 'data'])

omit 类似于 del,但支持同时删除多个键。

参见: omit, del

键路径(Keypath)检查

hasKeypaths(state, ['user'])
hasKeypaths(state, { 'user.profile.name': 'john' })

参见: hasKeypaths

获取值

values(state)

函数

简单函数

and(x, y)x && y
or(x, y)x || y
xor(x, y)!(!x && !y) && !(x && y)
equals(x, y)x === y
exists(x)!!x
not(x)!x

适用于函数组合。

参见: 以及, equals, exists

组合

compose(f, g)       // x => f(g(x))
curry(f)            // x => y => f(x, y)
flip(f)             // f(x, y) --> f(y, x)

参见: compose, curry, flip

与/或

passAll(f, g)       // x => f(x) && g(x)
passAny(f, g)       // x => f(x) || g(x)

参见: passAll, passAny

汇聚(Converge)

converge(and, [pluck('a'), pluck('b')])(x)
// → and(pluck(x, 'a'), pluck(x, 'b'))

参见: converge

数组

查找

find(list, x => x.y === 2)
findIndex(list, x => ...)
includes(list, 'item')
last(list)
find(list, hasProps('id'))

分组

groupBy(list, 'id')
indexBy(list, 'id')

示例

函数组合

isFloat = passAll(isNumber, compose(isInteger, not))
// n => isNumber(n) && not(isInteger(n))
function doStuff (object, options) { ... }

doStuffForce = curry(flip(doStuff))({ force: true })

参考资料