当前位置: 首页 > 编程日记 > 正文

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

小程序 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.

许多是由真棒库的启发Lodash和Ramda ! 我还编写了单元测试以确保行为正确。 您可以在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

相关文章:

洛谷1216 数字三角形

题目描述 观察下面的数字金字塔。 写一个程序来查找从最高点到底部任意处结束的路径,使路径经过数字的和最大。每一步可以走到左下方的点也可以到达右下方的点。 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5 在上面的样例中,从7 到 3 到 8 到 7 到 5 的路径产生了最大 …

iOS 依次执行 异步网络请求的一种实现

1.首先先介绍一个概念dispatch_semaphore dispatch_semaphore信号量为基于计数器的一种多线程同步机制。用于解决在多个线程访问共有资源时候,会因为多线程的特性而引发数据出错的问题.如果semaphore计数大于等于1,计数-1,返回,程…

那些有趣的Webview细节

最近公司的项目"一步"上用到了webview与js交互,主要是用google地图必须要安装有google pay,但是国内的手机都去掉了, 没办法只有用google地图的网页版了, 好在公司ios的小伙伴会h5,英语也不赖, 所…

二进制搜索树_二进制搜索树数据结构举例说明

二进制搜索树A tree is a data structure composed of nodes that has the following characteristics:树是由具有以下特征的节点组成的数据结构: Each tree has a root node (at the top) having some value. 每棵树都有一个具有某些值的根节点(在顶部)。 The roo…

无序数组及其子序列的相关问题研究

算法中以数组为研究对象的问题是非常常见的. 除了排序大家经常会遇到之外, 数组的子序列问题也是其中的一大分类. 今天我就对自己经常遇到的无序数组的子序列相关问题在这里总结一下. 前置条件: 给定无序数组. 以下所以的问题均以此为前置条件. 例如无序数组nums [2, 1, 3]. 问…

IOS使用正则表达式去掉html中的标签元素,获得纯文本

IOS使用正则表达式去掉html中的标签元素,获得纯文本 content是根据网址获得的网页源码字符串 NSRegularExpression *regularExpretion[NSRegularExpression regularExpressionWithPattern:"<[^>]*>|\n"options:0error:nil];content[regularExpretion string…

苹果禁止使用热更新 iOS开发程序员新转机来临

今天本是女神们的节日&#xff0c;所有iOS程序员沸腾了&#xff01;原因是苹果爸爸发狠了&#xff0c;部分iOS开发者收到了苹果的这封警告邮件&#xff1a; [图一 苹果邮件] 消息一出&#xff0c;一时间众多开发者众说纷纭&#xff0c;以下是来源于网络的各种看法&#xff1a;…

Python中的Lambda表达式

Lambda表达式 (Lambda Expressions) Lambda Expressions are ideally used when we need to do something simple and are more interested in getting the job done quickly rather than formally naming the function. Lambda expressions are also known as anonymous funct…

JAVA-初步认识-第十一章-object类-equals方法覆盖

一. 现在要谈论equals方法另一个方面。如果不写equals方法&#xff0c;直接用来比较也是可以的&#xff0c;貌似equals方法有点多余。 现在不比较对象是否相等&#xff0c;而是比较对象中的特定内容&#xff0c;比如说对象的年龄&#xff0c;之前的写法如下 其实这个方法写完后…

JPPhotoBrowserDemo--微信朋友圈浏览图片

JPPhotoBrowserDemo Browse picture like WeChat. GithubDemo 使用 CocoaPods pod JPPhotoBrowser 在使用的页面中 引用 #import "JPPhotoBrowserManager.h"下载使用 直接将下载文件中的 JPPhotoBrowser 文件夹拖入项目中在使用的页面中 引用 #import "JPPhot…

STM32F103 与 STM32F407引脚兼容问题

突袭网收集的解决方案如下 解决方案1&#xff1a; STM32F103有的功能407都有&#xff0c;并且这些功能的引脚完全兼容&#xff0c;只是程序不同而已。。。而STM32F407有的功能103不一定有&#xff0c;因为407强大些。。。。。。希望对你有用 解决方案2&#xff1a; 不能。407支…

getdate函数_SQL日期函数和GETDATE解释为带有语法示例

getdate函数There are 61 Date Functions defined in MySQL. Don’t worry, we won’t review them all here. This guide will give you an introduction to some of the common ones, and enough exposure for you to comfortably to explore on your own.MySQL中定义了61种日…

JPTagView-多样化的标签View

JPTagView Customized tag pages GitHubDemo 使用 CocoaPods pod JPTagView 在使用的页面中 引用 #import "JPTagView.h"下载使用 直接将下载文件中的 JPTagView 文件夹拖入项目中在使用的页面中 引用 #import "JPTagView.h"使用方法见demo

zsh 每次打开Terminal都需要source bash_profile问题

zsh 每次打开Terminal都需要source bash_profile问题 zsh加载的是 ~/.zshrc文件&#xff0c;而 ‘.zshrc’ 文件中并没有定义任务环境变量。 解决办法&#xff0c;在~/.zshrc文件最后&#xff0c;增加一行&#xff1a; source .bash_profile alias alias gs"git status&q…

解析json实例

解析项目目录中的一个json文件&#xff0c;将之转化为List的一个方法。 package com.miracles.p3.os.util;import com.miracles.p3.os.mode.VideoBean; import org.json.JSONArray; import org.json.JSONObject;import java.util.ArrayList; import java.util.List;/*** Create…

创建bdlink密码是数字_如何创建实际上是安全的密码

创建bdlink密码是数字I am very tired of seeing arbitrary password rules that are different for every web or mobile app. Its almost like these apps arent following a standard and are just making up their own rules that arent based on good security practices.…

通过分离dataSource 让我们的code具有更高的复用性.

转载自汪海的实验室 一 定义dataSource dataSource.h[objc] view plaincopytypedef void (^TableViewCellConfigureBlock)(id cell, id item); interface GroupNotificationDataSource : NSObject<UITableViewDataSource> - (id)initWithItems:(NSArray *)anItems …

复习心得 JAVA异常处理

java中的异常处理机制主要依赖于try&#xff0c;catch&#xff0c;finally&#xff0c;throw&#xff0c;throws五个关键字。其中&#xff0c; try关键字后紧跟一个花括号括起来的代码块&#xff08;花括号不可省略&#xff09;简称为try块。里面放置可能发生异常的代码。 catc…

Linux下Shell重定向

1. 标准输入&#xff0c;标准输出与标准错误输出 Linux下系统打开3个文件&#xff0c;标准输入&#xff0c;标准输出&#xff0c;标准错误输出。 标准输入:从键盘输入数据&#xff0c;即从键盘读入数据。 标准输出:把数据输出到终端上。 标准错误输出:把标准错误输出到终端上。…

sql avg函数使用格式_SQL AVG-SQL平均函数用语法示例解释

sql avg函数使用格式什么是SQL平均(AVG)函数&#xff1f; (What is the SQL Average (AVG) Function?) “Average” is an Aggregate (Group By) Function. It’s used to calculate the average of a numeric column from the set of rows returned by a SQL statement.“平均…

qml学习笔记(二):可视化元素基类Item详解(上半场anchors等等)

原博主博客地址&#xff1a;http://blog.csdn.net/qq21497936本文章博客地址&#xff1a;http://blog.csdn.net/qq21497936/article/details/78516201 qml学习笔记(二)&#xff1a;可视化元素基类Item详解&#xff08;上半场anchors等等&#xff09; 本学章节笔记主要详解Item元…

使用PowerShell登陆多台Windows,测试DCAgent方法

目标&#xff1a; 需要1台PC用域账户远程登陆10台PC&#xff0c;每台登陆后的PC执行发送敏感数据的操作后&#xff0c;再logoff。 在DCAgent服务器上&#xff0c;查看这10个用户每次登陆时&#xff0c;DCAgent是否能获取到登陆信息&#xff08;IP&#xff1a;User&#xff09; …

优雅地分离tableview回调

你是否遇到过这样的需求,在tableview中显示一列数据,点击某一个cell时&#xff0c;在此cell下显示相应的附加信息。如下图&#xff1a;你是不是觉得需求很容易实现&#xff0c;只要使用tableview的insertRowsAtIndexPaths:withRowAnimation:插入一个附加cell就可以了&#xff0…

next.js_Next.js手册

next.jsI wrote this tutorial to help you quickly learn Next.js and get familiar with how it works.我编写本教程是为了帮助您快速学习Next.js并熟悉其工作方式。 Its ideal for you if you have zero to little knowledge of Next.js, you have used React in the past,…

Redux 入门教程(一):基本用法

一年半前&#xff0c;我写了《React 入门实例教程》&#xff0c;介绍了 React 的基本用法。 React 只是 DOM 的一个抽象层&#xff0c;并不是 Web 应用的完整解决方案。有两个方面&#xff0c;它没涉及。代码结构组件之间的通信对于大型的复杂应用来说&#xff0c;这两方面恰恰…

Elasticsearch——Rest API中的常用用法

本篇翻译的是Elasticsearch官方文档中的一些技巧&#xff0c;是使用Elasticsearch必不可少的必备知识&#xff0c;并且适用于所有的Rest Api。 返回数据格式化 当在Rest请求后面添加?pretty时&#xff0c;结果会以Json格式化的方式显示。另外&#xff0c;如果添加?formatyaml…

Python几种主流框架

从GitHub中整理出的15个最受欢迎的Python开源框架。这些框架包括事件I/O&#xff0c;OLAP&#xff0c;Web开发&#xff0c;高性能网络通信&#xff0c;测试&#xff0c;爬虫等。 Django: Python Web应用开发框架Django 应该是最出名的Python框架&#xff0c;GAE甚至Erlang都有框…

Git Fetch vs Pull:Git Fetch和Git Pull命令之间有什么区别?

Git pull and fetch are two commands that are regularly used by Git users. Let’s see the difference between both commands.Git pull和fetch是Git用户经常使用的两个命令。 让我们看看两个命令之间的区别。 For the sake of context, it’s worth remembering that we’…

Redux 入门教程(二):中间件与异步操作

上一篇文章&#xff0c;我介绍了 Redux 的基本做法&#xff1a;用户发出 Action&#xff0c;Reducer 函数算出新的 State&#xff0c;View 重新渲染。但是&#xff0c;一个关键问题没有解决&#xff1a;异步操作怎么办&#xff1f;Action 发出以后&#xff0c;Reducer 立即算出…

day09_读写分离_组件介绍

mysql中间件研究&#xff08;Mysql-prxoy&#xff0c;Atlas&#xff0c;阿米巴&#xff0c;cobar&#xff0c;TDDL&#xff09;mysql-proxyMySQL Proxy就是这么一个中间层代理&#xff0c;简单的说&#xff0c;MySQL Proxy就是一个连接池&#xff0c;负责将前台应用的连接请求转…