【译】还来10个使用reduce制作的JavaScript实用函数

648 阅读3分钟

原文链接:yazeedb.com/posts/yet-a…
原作者:Yazeed Bzadough
翻译者:发呆小贤

总共30个函数!

这是我第三篇关于使用 reduce 制作实用函数的文章。

现在,我们总共有30个使用JavaScript的 reduce 实现的辅助函数了。有关 reduce 自身的更多详细信息,请考虑阅读我的 教程

下面列出的功能是由优秀的库 RamdaJS 所启发。我还编写了单元测试以确保行为正确,您可以在我的GitHub上找到它。

1. adjust

参数

  1. index - 源数组的索引
  2. fn - 应用于该索引的函数
  3. list - 列表

描述

将函数应用于给定索引处的值。如果提供的索引超出界限,则返回原始数组。

用例

const double = (x) => x * 2;

adjust(1, double, [1, 2, 3]);
// [1, 4, 3]

adjust(4, double, [1, 2, 3]);
// [1, 2, 3]

实现

const adjust = (index, fn, list) =>
  list.reduce((acc, value, sourceArrayIndex) => {
    const valueToUse = sourceArrayIndex === index ? fn(value) : value;

    acc.push(valueToUse);

    return acc;
  }, []);

2. fromPairs

参数

  1. pairs - 键值对列表

描述

根据键值对列表创建对象。

用例

fromPairs([['a', 1], ['b', 2], ['c', 3]]);
// { a: 1, b: 2, c: 3 }

实现

const fromPairs = (pairs) =>
  pairs.reduce((acc, currentPair) => {
    const [key, value] = currentPair;

    acc[key] = value;

    return acc;
  }, {});

3. range

参数

  1. from - 开始的数字
  2. to - 结束的数字

描述

返回一个给定范围的数字列表。

用例

range(1, 5);
// [1, 2, 3, 4, 5]

实现

const range = (from, to) =>
  Array.from({ length: to - from + 1 }).reduce((acc, _, index) => {
    acc.push(from + index);

    return acc;
  }, []);

4. repeat

参数

  1. item - 要重复的元素
  2. times - 重复的次数

描述

返回一个重复给定值N次的列表。

用例

repeat({ favoriteLanguage: 'JavaScript' }, 2);

/*
[{
    favoriteLanguage: 'JavaScript'
}, {
    favoriteLanguage: 'JavaScript'
}],
*/

实现

const repeat = (item, times) =>
  Array.from({ length: times }).reduce((acc) => {
    acc.push(item);

    return acc;
  }, []);

5. times

参数

  1. fn - 要调用的函数
  2. numTimes - 调用该函数的次数

描述

调用给定的函数N次。fn 接收当前索引作为参数。

用例

times((x) => x * 2, 3);
// [0, 2, 4]

实现

const times = (fn, numTimes) =>
  Array.from({ length: numTimes }).reduce((acc, _, index) => {
    acc.push(fn(index));

    return acc;
  }, []);

6. deduplicate

参数

  1. items - 项目列表

描述

对列表中的项目进行重复数据删除。

用例

deduplicate([[1], [1], { hello: 'world' }, { hello: 'world' }]);
// [[1], { hello: 'world' }]

实现

const deduplicate = (items) => {
  const cache = {};

  return items.reduce((acc, item) => {
    const alreadyIncluded = cache[item] === true;

    if (!alreadyIncluded) {
      cache[item] = true;
      acc.push(item);
    }

    return acc;
  }, []);
};

7. reverse

参数

  1. list - 列表

描述

反转一个列表生成新的数组而不改变它本身,和原生的 Array.reverse 方法不同。

用例

reverse([1, 2, 3]);
// [3, 2, 1]

实现

const reverse = (list) =>
  list.reduce((acc, _, index) => {
    const reverseIndex = list.length - index - 1;
    const reverseValue = list[reverseIndex];

    acc.push(reverseValue);

    return acc;
  }, []);

8. insertAll

参数

  1. index - 要插入的索引
  2. subList - 要插入的列表
  3. sourceList - 源列表

描述

将子列表插入到给定索引处的列表中。如果索引太大,则追加到列表的末尾。

用例

insertAll(1, [2, 3, 4], [1, 5]);
// [1, 2, 3, 4, 5]

insertAll(10, [2, 3, 4], [1, 5]);
// [1, 5, 2, 3, 4]

实现

const insertAll = (index, subList, sourceList) => {
  if (index > sourceList.length - 1) {
    return sourceList.concat(subList);
  }

  return sourceList.reduce((acc, value, sourceArrayIndex) => {
    if (index === sourceArrayIndex) {
      acc.push(...subList, value);
    } else {
      acc.push(value);
    }

    return acc;
  }, []);
};

9. mergeAll

参数

  1. objectList - 要合并的对象列表

描述

将对象列表合并为一个。

用例

mergeAll([
  { js: 'reduce' },
  { elm: 'fold' },
  { java: 'collect' },
  { js: 'reduce' }
]);

/*
{
    js: 'reduce',
    elm: 'fold',
    java: 'collect'
}
*/

实现

const mergeAll = (objectList) =>
  objectList.reduce((acc, obj) => {
    Object.keys(obj).forEach((key) => {
      acc[key] = obj[key];
    });

    return acc;
  }, {});

10. xprod

参数

  1. list1 - 列表1
  2. list2 - 列表2

描述

给定一个列表,返回所有可能对的新列表。

用例

xprod(['Hello', 'World'], ['JavaScript', 'Reduce']);
/*
[
  ['Hello', 'JavaScript'],
  ['Hello', 'Reduce'],
  ['World', 'JavaScript'],
  ['World', 'Reduce']
]
*/

实现

const xprod = (list1, list2) =>
  list1.reduce((acc, list1Item) => {
    list2.forEach((list2Item) => {
      acc.push([list1Item, list2Item]);
    });

    return acc;
  }, []);

传送门

【译】10分钟学会reduce

【译】使用reduce制作的10个JavaScript实用函数

【译】再来10个使用reduce制作的JavaScript实用函数