101 は、関数型プログラミングスタイルで不変(イミュータブル)データを扱うためのJavaScriptユーティリティライブラリです。
使い方 (Usage)
const isObject = require('101/isObject')
isObject({}) // → true
各関数はバンドルサイズを最小限に抑えるため、個別のモジュールとして提供されています。
See: 101 (GitHub)
型チェック (Type Checking)
isObject({})
isString('str')
isRegExp(/regexp/)
isBoolean(true)
isEmpty({})
isFunction(x => x)
isInteger(10)
isNumber(10.1)
instanceOf(obj, 'string')
オブジェクト操作 (Objects)
使用例
let obj = {}
更新 (Update)
obj = put(obj, 'user.name', 'John')
// → { user: { name: 'John' } }
取得 (Read)
pluck(name, 'user.name')
// → 'John'
削除 (Delete)
obj = del(obj, 'user')
// → { }
アクセサ (Accessors)
pluck(state, 'user.profile.name')
pick(state, ['user', 'ui'])
pick(state, /^_/)
pluck はネストされた特定の値を取得し、pick はオブジェクトのサブセットを返します。
セッター (Setters)
put(state, 'user.profile.name', 'john')
See: put
削除 (Deletion)
del(state, 'user.profile')
omit(state, ['user', 'data'])
omit は del に似ていますが、複数のキーを同時に除外できます。
キーパスの検証 (Keypath Verification)
hasKeypaths(state, ['user'])
hasKeypaths(state, { 'user.profile.name': 'john' })
See: hasKeypaths
値の取得 (Values)
values(state)
関数操作 (Functions)
コンビネータと単純関数
| 関数 | 同等の式 |
|---|---|
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 |
ポイントフリースタイルの関数型パイプラインや合成に最適です。
合成 (Composition)
compose(f, g) // x => f(g(x))
curry(f) // x => y => f(x, y)
flip(f) // f(x, y) --> f(y, x)
論理積と論理和 (Logical Conjunction & Disjunction)
passAll(f, g) // x => f(x) && g(x)
passAny(f, g) // x => f(x) || g(x)
収束 (Converge)
converge(and, [pluck('a'), pluck('b')])(x)
// → and(pluck(x, 'a'), pluck(x, 'b'))
See: converge
配列操作 (Arrays)
検索と述語関数 (Search & Predicates)
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 })