Javascript集合操作

基于Lodash

常见集合操作

过滤、遍历、遍历跳出

不可变集合

添加

const a = [1, 2, 3];
const b = [...a, 4, 5];

删除

const a = [1, 2, 3];
const b = _.filter(a, v => v !== 2);

修改

const a = [1, 2, 3];
const b = _.map(a, v => v === 2 ? 4 : v)

来点复杂的

const a = [{
  name: 'Tom',
  friends: [{ name: 'Jerry' }],
  age: 2
}, {
  name: 'Robert',
  friends: [
    { name: 'Tom' },
    { name: 'Jerry' }
  ],
  age: 4
}];

// TODO: 为Tom添加一个到Robert的朋友

异步集合操作

需求

  • 在数据库中创建三条主记录和一条子记录。如下:
    • t1
      • t22
    • t2
    • t3
  • 然后查询并输出这些记录

ECMAScript 5

Test.create({name: 't1'}, function(t1) {
  Test.create({name: 't2'}, function(t2) {
    Test.create({name: 't3'}, function(t3) {
      Test2.create({name: 't11', testId: t1.id},
        output);
    });
  });
});

With Promise Pattern

Test.create({name: 't1'})
    .then(function(t1) {
      Test.create({name: 't2'})
          .then(function (t2) {
            Test.create({name: 't3'})
                .then(function(t3) {
                  Test2.create(
                        {
                            name: 't11',
                            testId: t1.id
                        })
                      .then(output);
                });
          });
    });

基本范式

Parallel Map (并行映射)

async function parallelMap(urls: Array<string>) {
    return Promise.all(_.map(
        urls,
        async (url) => {
            const res = await fetch(url);
            if (!res.ok) {
                throw new Error('fetch failed.');
            }
            const result = await res.json();
            return result;
        }
    ));
}

Serially Map (串行映射)

async function seriallyMap(urls: Array<string>) {
    const results = [];
    await _.reduce(
        urls,
        async (pms, url) => {
            await pms;
            const res = await fetch(url);
            if (!res.ok) {
                throw new Error('fetch failed.');
            }
            const result = await res.json();
            results.push(result);
        },
        Promise.resolve()
    );
    return results;
}

Serially for each (串行遍历)

Javascript集合操作 -- 基于Lodash (未完成)

By Colin Han

Javascript集合操作 -- 基于Lodash (未完成)

  • 1,309