本文共 7397 字,大约阅读时间需要 24 分钟。
小程序 reduce
This time, with a test suite!
这次,带有测试套件!
I wrote about 10 utility functions implemented with JavaScript's . 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的实现的实用 。 它广受好评,我对这种宏伟的多功能工具怀有更深的欣赏。 为什么不再尝试10个呢?
Many of these were inspired by the awesome libraries and ! I also wrote unit tests to ensure correct behavior. You can see everything on the .
许多是由真棒库的启发和 ! 我还编写了单元测试以确保行为正确。 您可以在上看到所有内容。
...functions
- Any number of functions.
...functions
任何数量的功能。
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.
执行从左到右的功能合成。 管道的第一个参数用作初始值,并在通过每个函数时进行转换。
const pipe = (...functions) => (initialValue) => functions.reduce((value, fn) => fn(value), initialValue);
const mathSequence = pipe( (x) => x * 2, (x) => x - 1, (x) => x * 3 ); mathSequence(1); // 3mathSequence(2); // 9mathSequence(3); // 15
For more detail, I wrote an .
有关更多详细信息,我写了的 。
...functions
- Any number of functions.
...functions
任何数量的功能。
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
,但方向相反。
const compose = (...functions) => (initialValue) => functions.reduceRight((value, fn) => fn(value), initialValue);
const mathSequence = compose( (x) => x * 2, (x) => x - 1, (x) => x * 3 ); mathSequence(1); // 4mathSequence(2); // 10mathSequence(3); // 16
For more detail, I wrote an .
有关更多详细信息,我写了的 。
list1
- List of items.
list1
项目列表。
list2
- List of items.
list2
项目列表。
Pairs items from two lists via index. If list lengths are not equal, the shorter list's length is used.
通过索引配对两个列表中的项目。 如果列表长度不相等,则使用较短列表的长度。
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; }, []);};
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!']]
separator
- Item to insert.
separator
-要插入的项目。
list
- List of items.
list
项目列表。
Inserts a separator between each element of a list.
在列表的每个元素之间插入分隔符。
const intersperse = (separator, list) => list.reduce((acc, value, index) => { if (index === list.length - 1) { acc.push(value); } else { acc.push(value, separator); } return acc; }, []);
intersperse('Batman', [1, 2, 3, 4, 5, 6]);// [1, 'Batman', 2, 'Batman', 3, 'Batman', 4, 'Batman', 5, 'Batman', 6]intersperse('Batman', []);// []
index
- Index to insert element at.
index
插入元素的索引。
newItem
- Element to insert.
newItem
要插入的元素。
list
- List of items.
list
项目列表。
Inserts an element at the given index. If the index is too large, element is inserted at the end of the list.
在给定索引处插入一个元素。 如果索引太大,则将元素插入列表的末尾。
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; }, []);};
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']]
list
- List of items.
list
项目列表。
Flattens a list of items by one level.
将项目列表展平一级。
const flatten = (list) => list.reduce((acc, value) => acc.concat(value), []);
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]]
mappingFunction
- Function to run on each list item.
mappingFunction
在每个列表项上运行的函数。
list
- List of items.
list
项目列表。
Maps each list item according to the given function, then flattens the result.
根据给定的功能映射每个列表项,然后展平结果。
// Kind of cheating, because we already implemented flatten 😉const flatMap = (mappingFunction, list) => flatten(list.map(mappingFunction));
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']
item
- Item to check the list for.
item
-项目检查清单。
list
- List of items.
list
项目列表。
Checks a list for a given element. If the element is found, returns true
. Otherwise returns false
.
检查给定元素的列表。 如果找到该元素,则返回true
。 否则返回false
。
const includes = (item, list) => list.reduce((isIncluded, value) => isIncluded || item === value, false);
includes(3, [1, 2, 3]); // trueincludes(3, [1, 2]); // falseincludes(0, []); // false
list
- List of items.
list
项目列表。
Removes "falsey" values from a list.
从列表中删除“假”值。
const compact = (list) => list.reduce((acc, value) => { if (value) { acc.push(value); } return acc; }, []);
compact([0, null, 1, undefined, 2, '', 3, false, 4, NaN]);// [1, 2, 3, 4]
key
- String to use as the new object key.
key
-字符串作为新对象键使用。
list
- List of items.
list
项目列表。
Converts an array into an object, using the given key as the new object's key.
使用给定键作为新对象的键,将数组转换为对象。
const arrayIntoObject = (key, list) => list.reduce((acc, obj) => { const value = obj[key]; acc[value] = obj; return acc; }, {});
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' }}*/
If you'd like to schedule a free call to discuss Front-End development questions regarding code, interviews, career, or anything else .
如果您想安排免费电话讨论有关代码,面试,职业或其他方面的前端开发问题,请 。
After that if you enjoy our first meeting, we can discuss an ongoing coaching to help you reach your Front-End development goals!
之后,如果您喜欢我们的第一次会议,我们可以讨论一个持续的教练,以帮助您实现前端开发目标!
For more content like this, check out
有关更多内容,请访问
Until next time!
直到下一次!
翻译自:
小程序 reduce
转载地址:http://eduzd.baihongyu.com/