小程序 reduce_用reduce制作的另外10个实用程序功能

小程序 reduce

Thirty functions total!

共有30个功能!

This is my third article on Utility Functions Made with Reduce.

这是我的第三篇有关用Reduce制作的效用函数的文章。

Altogether we now have thirty helper functions made using JavaScript's reduce. For more detail on reduce itself, consider reading my tutorial on it.

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

The functions listed below were inspired by the amazing RamdaJS library. I also wrote unit tests to ensure correct behavior, which you can find on my GitHub.

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

1.调整 (1. adjust)

参量 (Parameters)

  1. index - Index of source array

    index源数组的索引

  2. fn - Function to apply at that index

    fn在该index处应用的函数

  3. list - List of items.

    list项目列表。

描述 (Description)

Applies a function to the value at the given index. Returns the original array if provided index is out of bounds.

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

用法 (Usage)

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

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

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

实作 (Implementation)

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

    acc.push(valueToUse);

    return acc;
  }, []);

2. fromPairs (2. fromPairs)

参量 (Parameters)

  1. pairs - A list of key-value pairs.

    pairs -键值对列表。

描述 (Description)

Creates an object from a list of key-value pairs.

从键值对列表创建对象。

用法 (Usage)

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

实作 (Implementation)

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

    acc[key] = value;

    return acc;
  }, {});

3.范围 (3. range)

参量 (Parameters)

  1. from - Starting number.

    from -起始编号。

  2. to - Ending number.

    to -结束号码。

描述 (Description)

Returns a list of numbers from a given range.

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

用法 (Usage)

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

实作 (Implementation)

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

    return acc;
  }, []);

4.重复 (4. repeat)

参量 (Parameters)

  1. item - Item to repeat.

    item -项目重复。

  2. times - Number of times to repeat.

    times重复的次数。

描述 (Description)

Returns a list of a given value N times.

返回N次给定值的列表。

用法 (Usage)

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

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

实作 (Implementation)

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

    return acc;
  }, []);

5次 (5. times)

参量 (Parameters)

  1. fn - Function to call.

    fn调用函数。

  2. numTimes - Number of times to call that function.

    numTimes调用该函数的次数。

描述 (Description)

Calls a given function N times. The fn provided receives the current index as a parameter.

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

用法 (Usage)

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

实作 (Implementation)

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

    return acc;
  }, []);

6.重复数据删除 (6. deduplicate)

参量 (Parameters)

  1. items - List of items.

    items列表。

描述 (Description)

Deduplicates the items in a list.

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

用法 (Usage)

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

实作 (Implementation)

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.反向 (7. reverse)

参量 (Parameters)

  1. list - List of items.

    list项目列表。

描述 (Description)

Reverses a list without mutating it by returning a new list, unlike the native Array.reverse method.

与本机Array.reverse方法不同,在通过返回新列表而对其进行突变的情况下,对列表进行Array.reverse处理。

用法 (Usage)

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

实作 (Implementation)

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

    acc.push(reverseValue);

    return acc;
  }, []);

8. insertAll (8. insertAll)

参量 (Parameters)

  1. index - Index to insert at.

    index -指数在插入。

  2. subList - List to insert.

    subList要插入的列表。

  3. sourceList - Source list.

    sourceList源列表。

描述 (Description)

Inserts a sub-list into a list at the given index. Appends to the end of the list if index is too large.

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

用法 (Usage)

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

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

实作 (Implementation)

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 (9. mergeAll)

参量 (Parameters)

  1. objectList - List of objects to merge.

    objectList要合并的对象列表。

描述 (Description)

Merges a list of objects into one.

将对象列表合并为一个。

用法 (Usage)

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

实作 (Implementation)

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

    return acc;
  }, {});

10. xprod (10. xprod)

参量 (Parameters)

  1. list1 - List of items.

    list1项目列表。

  2. list2 - List of items.

    list2项目列表。

描述 (Description)

Given a list, returns a new list of all possible pairs.

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

用法 (Usage)

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

实作 (Implementation)

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

    return acc;
  }, []);

需要免费辅导吗? (Want Free Coaching?)

If you'd like to schedule a free call to discuss Front-End development questions regarding code, interviews, career, or anything else follow me on Twitter and DM me.

如果您想安排免费电话讨论有关代码,面试,职业或其他方面的前端开发问题,请在Twitter和DM me上关注我

After that if you enjoy our first meeting, we can discuss an ongoing coaching to help you reach your Front-End development goals!

之后,如果您喜欢我们的第一次会议,我们可以讨论一个持续的教练,以帮助您实现前端开发目标!

谢谢阅读 (Thanks for reading)

For more content like this, check out https://yazeedb.com!

有关更多内容,请访问https://yazeedb.com!

Until next time!

直到下一次!

翻译自: https://www.freecodecamp.org/news/yet-another-10-utils-using-reduce/

小程序 reduce

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值