immutability-util - JavaScript immutable data 模块


MIT
跨平台
JavaScript

软件简介

immutability-util

一个关于 immutable data 处理的 JavaScript 模块,不修改原始值获得一份数据拷贝。使用 ES6
预发重写,并主要集中在性能以及更加好用的 API。

1. 特性

  1. 链式 API 调用,使用非常方便;

  2. 通过 path string 的方式寻找需要修改的节点,简化代码;

  3. 也许可以获得更好的性能;

2. 安装使用

使用 NPM 下载:

npm install -S immutability-util

然后使用方法如下:

const iu = require('immutability-util');
// or 
import iu from 'immutability-util';

// obj need to be mutated.
var obj = {
  a: 1,
  b: 2,
  c: {
    d: 3,
    e: {
      f: [4, 5, 6],
      g: {
        h: 'iu',
      },
    },
    i: {
      j: 'hello, world.',
      k: [7, 8, 9],
      l: [10, 11, 12],
    }
  },
};

// chainable usage.
const state = iu(state)
  .$apply(['a'], v => v + 1)
  .$merge(['c', 'e', 'g'], { m: 'update'})
  .$push(['c', 'e', 'f'], [7, 8, 9])
  .$set(['c', 'i', 'j'], 'hello node 8.')
  .$splice(['c', 'i', 'k'], [1, 1, 10])
  .$unset(['c'], ['d'])
  .$unshift(['c', 'i', 'l'], [13])
  .value(); // then get the mutated copy.
  
// or use path string.
iu(obj).$set('c.i.j', 'hello node 8.').value();

另外,也可以使用以下的方式处理数组路由;

const obj = {
  a: {
    b: [{
      c: [1, 2, 3],
    }, {
      d: 4,
    }, {
      e: [5, 6],
    }]
  }
};
const state = iu(obj)
  .$apply('a.b[1].d', v => v + 1)
  .$push('a.b[0].c', [4])
  .$set('a.b[2].e[0]', 'hello node 8.')
  .value();

3. 可用的 API

当获得了 ImmutabilityUtil 的实例后(引入模块就获得了),可以使用以下的方法:

  • $apply(path, function): 传入一个 function,并且把当前节点作为值传入;

  • $merge(path, object): 类似于数组的 merge 操作;

  • $push(path, array): 类似于数组的 push 操作;

  • $set(path, any): 直接替换对应位置的数据;

  • $splice(path, array_of_arrays): 类似于数组的 splice 方法;

  • $unset(path, array_of_strings): 删除键值;类似于 delete 方法;

  • $unshift(path, array): 类似于数组的 unshift 方法;

然后就可以使用 API value() 得到 immutable 数据拷贝。欢迎 pr 更多的操作方法;

4. Build & Test

通过下面的命令来 buikd 和测试:

npm run build
# run the testcases
npm run test

也可以运行 npm run benchmark 来查看性能对比。

5. License

MIT@hustcc.