小程序 reduce_使用reduce制作的10个更多实用程序功能

本文介绍了使用JavaScript的reduce函数实现的10个实用功能,包括管(pipe)、撰写(compose)、拉链(zip)、穿插(intersperse)等。每个功能都包含参数、描述、实现和用法,部分灵感来源于Lodash和Ramda库,并附有单元测试以确保正确性。
摘要由CSDN通过智能技术生成

小程序 reduce

This time, with a test suite!

这次,带有测试套件!

Previously I wrote about 10 utility functions implemented with JavaScript's reduce function. It was well-received, and I walked away with an even deeper appreciation for this magnificent multi-tool. Why not try 10 more?

之前,我写了约10个使用JavaScript的reduce函数实现的实用函数 。 它广受好评,我对这种宏伟的多功能工具怀有更深的欣赏。 为什么不再尝试10个呢?

Many of these were inspired by the awesome libraries Lodash and Ramda! I also wrote unit tests to ensure correct behavior. You can see everything on the Github repo here.

许多是由真棒库的启发LodashRamda ! 我还编写了单元测试以确保行为正确。 您可以在Github仓库上看到所有内容。

1.管 (1. pipe)

参量 (Parameters)

  1. ...functions - Any number of functions.

    ...functions任何数量的功能。

描述 (Description)

Performs left-to-right function composition. The first argument to a pipeline acts as the initial value, and is transformed as it passes through each function.

执行从左到右的功能合成。 管道的第一个参数用作初始值,并在通过每个函数时进行转换。

实作 (Implementation)

const pipe = (...functions) => (initialValue) =>
  functions.reduce((value, fn) => fn(value), initialValue);

用法 (Usage)

const mathSequence = pipe(
    (x) => x * 2,
    (x) => x - 1,
    (x) => x * 3
  );
  
mathSequence(1); // 3
mathSequence(2); // 9
mathSequence(3); // 15

For more detail, I wrote an article on pipe here.

有关更多详细信息,我在这里写了一篇关于pipe文章

2.撰写 (2. compose)

参量 (Parameters)

  1. ...functions - Any number of functions.

    ...functions任何数量的功能。

描述 (Description)

Performs right-to-left function composition. The first argument to a pipeline acts as the initial value, and is transformed as it passes through each function.

执行从右到左的功能合成。 管道的第一个参数用作初始值,并在通过每个函数时进行转换。

Works like pipe, but in the opposite direction.

类似于pipe ,但方向相反。

实作 (Implementation)

const compose = (...functions) => (initialValue) =>
  functions.reduceRight((value, fn) => fn(value), initialValue);

用法 (Usage)

const mathSequence = compose(
    (x) => x * 2,
    (x) => x - 1,
    (x) => x * 3
  );
  
mathSequence(1); // 4
mathSequence(2); // 10
mathSequence(3); // 16

For more detail, I wrote an article on compose here.

有关更多详细信息,我在这里写了一篇关于compose文章

3.拉链 (3. zip)

参量 (Parameters)

  1. list1 - List of items.

    list1项目列表。

  2. list2 - List of items.

    list2项目列表。

描述 (Description)

Pairs items from two lists via index. If list lengths are not equal, the shorter list's length is used.

通过索引配对两个列表中的项目。 如果列表长度不相等,则使用较短列表的长度。

实作 (Implementation)

const zip = (list1, list2) => {
  const sourceList = list1.length > list2.length ? list2 : list1;

  return sourceList.reduce((acc, _, index) => {
    const value1 = list1[index];
    const value2 = list2[index];

    acc.push([value1, value2]);

    return acc;
  }, []);
};

用法 (Usage)

zip([1, 3], [2, 4]); // [[1, 2], [3, 4]]

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

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

zip(['Decode', 'secret'], ['this', 'message!']);
// [['Decode', 'this'], ['secret', 'message!']]

4.穿插 (4. intersperse)

参量 (Parameters)

  1. separator - Item to insert.

    separator -要插入的项目。

  2. list - List of items.

    list项目列表。

描述 (Description)

Inserts a separator between each element of a list.

在列表的每个元素之间插入分隔符。

实作 (Implementation)

const intersperse = (separator, list) =>
  list.reduce((acc, value, index) => {
    if (index === list.length - 1) {
      acc.push(value);
    } else {
      acc.push(value, separator);
    }

    return acc;
  }, []);

用法 (Usage)

intersperse('Batman', [1, 2, 3, 4, 5, 6]);
// [1, 'Batman', 2, 'Batman', 3, 'Batman', 4, 'Batman', 5, 'Batman', 6]

intersperse('Batman', []);
// []

5.插入 (5. insert)

参量 (Parameters)

  1. index - Index to insert element at.

    index插入元素的索引。

  2. newItem - Element to insert.

    newItem要插入的元素。

  3. list - List of items.

    list项目列表。

描述 (Description)

Inserts an element at the given index. If the index is too large, element is inserted at the end of the list.

在给定索引处插入一个元素。 如果索引太大,则将元素插入列表的末尾。

实作 (Implementation)

const insert = (index, newItem, list) => {
  if (index > list.length - 1) {
    return [...list, newItem];
  }

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

    return acc;
  }, []);
};

用法 (Usage)

insert(0, 'Batman', [1, 2, 3]);
// ['Batman', 1, 2, 3]

insert(1, 'Batman', [1, 2, 3]);
// [1, 'Batman', 2, 3]

insert(2, ['Batman'], [1, 2, 3]);
// [1, 2, ['Batman'], 3]

insert(10, ['Batman'], [1, 2, 3]);
// [1, 2, 3, ['Batman']]

6.展平 (6. flatten)

参量 (Parameters)

  1. list - List of items.

    list项目列表。

描述 (Description)

Flattens a list of items by one level.

将项目列表展平一级。

实作 (Implementation)

const flatten = (list) => list.reduce((acc, value) => acc.concat(value), []);

用法 (Usage)

flatten([[1, 2], [3, 4]]);
// [1, 2, 3, 4]

flatten([[1, 2], [[3, 4]]]);
// [1, 2, [3, 4]]

flatten([[[1, 2]], [3, 4]]);
// [[1, 2], 3, 4]

flatten([[[1, 2], [3, 4]]]);
// [[1, 2], [3, 4]]

7. flatMap (7. flatMap)

参量 (Parameters)

  1. mappingFunction - Function to run on each list item.

    mappingFunction在每个列表项上运行的函数。

  2. list - List of items.

    list项目列表。

描述 (Description)

Maps each list item according to the given function, then flattens the result.

根据给定的功能映射每个列表项,然后展平结果。

实作 (Implementation)

// Kind of cheating, because we already implemented flatten 😉
const flatMap = (mappingFunction, list) => flatten(list.map(mappingFunction));

用法 (Usage)

flatMap((n) => [n * 2], [1, 2, 3, 4]);
// [2, 4, 6, 8]

flatMap((n) => [n, n], [1, 2, 3, 4]);
// [1, 1, 2, 2, 3, 3, 4, 4]

flatMap((s) => s.split(' '), ['flatMap', 'should be', 'mapFlat']);
// ['flatMap', 'should', 'be', 'mapFlat']

8.包括 (8. includes)

参量 (Parameters)

  1. item - Item to check the list for.

    item -项目检查清单。

  2. list - List of items.

    list项目列表。

描述 (Description)

Checks a list for a given element. If the element is found, returns true. Otherwise returns false.

检查给定元素的列表。 如果找到该元素,则返回true 。 否则返回false

实作 (Implementation)

const includes = (item, list) =>
  list.reduce((isIncluded, value) => isIncluded || item === value, false);

用法 (Usage)

includes(3, [1, 2, 3]); // true
includes(3, [1, 2]); // false
includes(0, []); // false

9.紧凑 (9. compact)

参量 (Parameters)

  1. list - List of items.

    list项目列表。

描述 (Description)

Removes "falsey" values from a list.

从列表中删除“假”值。

实作 (Implementation)

const compact = (list) =>
  list.reduce((acc, value) => {
    if (value) {
      acc.push(value);
    }

    return acc;
  }, []);

用法 (Usage)

compact([0, null, 1, undefined, 2, '', 3, false, 4, NaN]);
// [1, 2, 3, 4]

10. arrayIntoObject (10. arrayIntoObject)

参量 (Parameters)

  1. key - String to use as the new object key.

    key -字符串作为新对象键使用。

  2. list - List of items.

    list项目列表。

描述 (Description)

Converts an array into an object, using the given key as the new object's key.

使用给定键作为新对象的键,将数组转换为对象。

实作 (Implementation)

const arrayIntoObject = (key, list) =>
  list.reduce((acc, obj) => {
    const value = obj[key];

    acc[value] = obj;

    return acc;
  }, {});

用法 (Usage)

const users = [
    { username: 'JX01', status: 'offline' },
    { username: 'yazeedBee', status: 'online' }
];

arrayIntoObject('username', users);
/*
{
  JX01: {
    username: 'JX01',
    status: 'offline'
  },
  yazeedBee: { username: 'yazeedBee', status: 'online' }
}
*/

arrayIntoObject('status', users);
/*
{
  offline: {
    username: 'JX01',
    status: 'offline'
  },
  online: { username: 'yazeedBee', status: 'online' }
}
*/

需要免费辅导吗? (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/10-more-js-utils-using-reduce/

小程序 reduce

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值