小程序 reduce_使用Reduce制作的10个JavaScript实用程序功能
小程序 reduce
The multi-tool strikes again.
多功能工具再次触击。
In my last article I offered you a challenge to recreate well-known functions using reduce
. This article will show you how some of them can be implemented, along with some extras!
在上一篇文章中,我向您提出了使用reduce
来重新创建知名函数的挑战。 本文将向您展示如何实现其中的一些功能以及一些其他功能!
In total we're going to look at ten utility functions. They're incredibly handy on your projects, and best of all, they're implemented using reduce
! I drew lots of inspiration from the RamdaJS library for this one, so check that out!
总共我们将要看十个实用函数。 它们在您的项目上非常方便,而且最重要的是,它们使用reduce
来实现! 我从RamdaJS库中汲取了很多灵感,所以请检查一下!
1.一些 (1. some)
参量 (Parameters)
predicate
- Function that returnstrue
orfalse
.predicate
-返回true
或false
函数。array
- List of items to test.array
要测试的项目列表。
描述 (Description)
If predicate
returns true
for any item, some
returns true
. Otherwise it returns false
.
如果predicate
返回true
任何项目, some
返回true
。 否则返回false
。
实作 (Implementation)
const some = (predicate, array) =>array.reduce((acc, value) => acc || predicate(value), false);
用法 (Usage)
const equals3 = (x) => x === 3;some(equals3, [3]); // true
some(equals3, [3, 3, 3]); // true
some(equals3, [1, 2, 3]); // true
some(equals3, [2]); // false
2.全部 (2. all)
参量 (Parameters)
predicate
- Function that returnstrue
orfalse
.predicate
-返回true
或false
函数。array
- List of items to test.array
要测试的项目列表。
描述 (Description)
If predicate
returns true
for every item, all
returns true
. Otherwise it returns false
.
如果predicate
返回true
为每个项目, all
返回true
。 否则返回false
。
实作 (Implementation)
const all = (predicate, array) =>array.reduce((acc, value) => acc && predicate(value), true);
用法 (Usage)
const equals3 = (x) => x === 3;all(equals3, [3]); // true
all(equals3, [3, 3, 3]); // true
all(equals3, [1, 2, 3]); // false
all(equals3, [3, 2, 3]; // false
3.无 (3. none)
参量 (Parameters)
predicate
- Function that returnstrue
orfalse
.predicate
-返回true
或false
函数。array
- List of items to test.array
要测试的项目列表。
描述 (Description)
If predicate
returns false
for every item, none
returns true
. Otherwise it returns false
.
如果predicate
对每个项目返回false
,则none
返回true
。 否则返回false
。
实作 (Implementation)
const none = (predicate, array) =>array.reduce((acc, value) => !acc && !predicate(value), false);
用法 (Usage)
const isEven = (x) => x % 2 === 0;none(isEven, [1, 3, 5]); // true
none(isEven, [1, 3, 4]); // false
none(equals3, [1, 2, 4]); // true
none(equals3, [1, 2, 3]); // false
4.地图 (4. map)
参量 (Parameters)
transformFunction
- Function to run on each element.transformFunction
在每个元素上运行的函数。array
- List of items to transform.array
要转换的项目列表。
描述 (Description)
Returns a new array of items, each one transformed according to the given transformFunction
.
返回一个新的项目数组,每个数组均根据给定的transformFunction
。
实作 (Implementation)
const map = (transformFunction, array) =>array.reduce((newArray, item) => {newArray.push(transformFunction(item));return newArray;}, []);
用法 (Usage)
const double = (x) => x * 2;
const reverseString = (string) =>string.split('').reverse().join('');map(double, [100, 200, 300]);
// [200, 400, 600]map(reverseString, ['Hello World', 'I love map']);
// ['dlroW olleH', 'pam evol I']
5.过滤器 (5. filter)
参量 (Parameters)
predicate
- Function that returnstrue
orfalse
.predicate
-返回true
或false
函数。array
- List of items to filter.array
要过滤的项目列表。
描述 (Description)
Returns a new array. If predicate
returns true
, that item is added to the new array. Otherwise that item is excluded from the new array.
返回一个新数组。 如果predicate
返回true
,则该项目将添加到新数组中。 否则,该项目将从新数组中排除。
实作 (Implementation)
const filter = (predicate, array) =>array.reduce((newArray, item) => {if (predicate(item) === true) {newArray.push(item);}return newArray;}, []);
用法 (Usage)
const isEven = (x) => x % 2 === 0;filter(isEven, [1, 2, 3]);
// [2]filter(equals3, [1, 2, 3, 4, 3]);
// [3, 3]
6.拒绝 (6. reject)
参量 (Parameters)
predicate
- Function that returnstrue
orfalse
.predicate
-返回true
或false
函数。array
- List of items to filter.array
要过滤的项目列表。
描述 (Description)
Just like filter
, but with the opposite behavior.
就像filter
一样,但是行为相反。
If predicate
returns false
, that item is added to the new array. Otherwise that item is excluded from the new array.
如果predicate
返回false
,则该项目将添加到新数组中。 否则,该项目将从新数组中排除。
实作 (Implementation)
const reject = (predicate, array) =>array.reduce((newArray, item) => {if (predicate(item) === false) {newArray.push(item);}return newArray;}, []);
用法 (Usage)
const isEven = (x) => x % 2 === 0;reject(isEven, [1, 2, 3]);
// [1, 3]reject(equals3, [1, 2, 3, 4, 3]);
// [1, 2, 4]
7.找到 (7. find)
参量 (Parameters)
predicate
- Function that returnstrue
orfalse
.predicate
-返回true
或false
函数。array
- List of items to search.array
要搜索的项目列表。
描述 (Description)
Returns the first element that matches the given predicate
. If no element matches then undefined
is returned.
返回与给定predicate
匹配的第一个元素。 如果没有元素匹配,则返回undefined
。
实作 (Implementation)
const find = (predicate, array) =>array.reduce((result, item) => {if (result !== undefined) {return result;}if (predicate(item) === true) {return item;}return undefined;}, undefined);
用法 (Usage)
const isEven = (x) => x % 2 === 0;find(isEven, []); // undefined
find(isEven, [1, 2, 3]); // 2
find(isEven, [1, 3, 5]); // undefined
find(equals3, [1, 2, 3, 4, 3]); // 3
find(equals3, [1, 2, 4]); // undefined
8.分区 (8. partition)
参量 (Parameters)
predicate
- Function that returnstrue
orfalse
.predicate
-返回true
或false
函数。array
- List of items.array
项目列表。
描述 (Description)
"Partitions" or splits an array into two based on the predicate
. If predicate
returns true
, the item goes into list 1. Otherwise the item goes into list 2.
根据predicate
“分区”或将数组拆分为两个。 如果predicate
返回true
,则该项目进入列表1。否则,该项目进入列表2。
实作 (Implementation)
const partition = (predicate, array) =>array.reduce((result, item) => {const [list1, list2] = result;if (predicate(item) === true) {list1.push(item);} else {list2.push(item);}return result;},[[], []]);
用法 (Usage)
const isEven = (x) => x % 2 === 0;partition(isEven, [1, 2, 3]);
// [[2], [1, 3]]partition(isEven, [1, 3, 5]);
// [[], [1, 3, 5]]partition(equals3, [1, 2, 3, 4, 3]);
// [[3, 3], [1, 2, 4]]partition(equals3, [1, 2, 4]);
// [[], [1, 2, 4]]
9.拔 (9. pluck)
参量 (Parameters)
key
- Key name to pluck from the objectkey
-要从对象中选取的键名称array
- List of items.array
项目列表。
描述 (Description)
Plucks the given key
off of each item in the array. Returns a new array of these values.
将给定的key
从数组中的每个项目中拔出。 返回这些值的新数组。
实作 (Implementation)
const pluck = (key, array) =>array.reduce((values, current) => {values.push(current[key]);return values;}, []);
用法 (Usage)
pluck('name', [{ name: 'Batman' }, { name: 'Robin' }, { name: 'Joker' }]);
// ['Batman', 'Robin', 'Joker']pluck(0, [[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
// [1, 4, 7]
10.扫描 (10. scan)
参量 (Parameters)
reducer
- Standard reducer function that receives two parameters - the accumulator and current element from the array.reducer
标准的reducer函数,它接收两个参数-数组中的累加器和当前元素。initialValue
- The initial value for the accumulator.initialValue
累加器的初始值。array
- List of items.array
项目列表。
描述 (Description)
Works just like reduce
but instead just the single result, it returns a list of every reduced value on the way to the single result.
就像reduce
一样工作,但只是单个结果,它会返回通往单个结果的每个减少值的列表。
实作 (Implementation)
const scan = (reducer, initialValue, array) => {const reducedValues = [];array.reduce((acc, current) => {const newAcc = reducer(acc, current);reducedValues.push(newAcc);return newAcc;}, initialValue);return reducedValues;
};
用法 (Usage)
const add = (x, y) => x + y;
const multiply = (x, y) => x * y;scan(add, 0, [1, 2, 3, 4, 5, 6]);
// [1, 3, 6, 10, 15, 21] - Every number added from 1-6scan(multiply, 1, [1, 2, 3, 4, 5, 6]);
// [1, 2, 6, 24, 120, 720] - Every number multiplied from 1-6
需要免费辅导吗? (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-js-util-functions-in-reduce/
小程序 reduce
相关文章:

流媒体,hls
所谓流媒体是指采用流式传输的方式在Internet播放的媒体格式。流媒体又叫流式媒体,它是指商家用一个视频传送服务器把节目当成数据包发出,传送到网络上。用户通过解压设备对这些数据进行解压后,节目就会像发送前那样显示出来。流媒体…

uniapp实现页面左右滑动,上下滑动事件
实现代码: <view class"" touchstart"touchstart" touchend"touchend"> </view> data() {return {touchData: {}, //滑动事件数据} } methods: {touchstart(e) {this.touchData.clientX e.changedTouches[0].clientX;…

android逆向分析概述_Android存储概述
android逆向分析概述Storage is this thing we are all aware of, but always take for granted. Not long ago, every leap in storage capacity was incremental and appeared to be impossible. Nowadays, we don’t give a second thought when contemplating how much of …

小程序地图的使用笔记
这两天在看小程序的地图,写写笔记记录一下 小程序官方文档提供的方法 https://mp.weixin.qq.com/debug/wxadoc/dev/api/location.html 腾讯地图提供的jssdk http://lbs.qq.com/qqmap_wx_jssdk/qqmapwx.html 根据提示使用腾讯地图jssdk需要申请,在实例化的…

JS 实现可停顿的垂直滚动
1 var ScrollMiddle {2 Odiv:document.getElementById(comment), // 目标DOM 3 Oli: document.getElementById(comment).getElementsByTagName(li), 4 times:30, // 配置滚动时间 …

uniapp 上拉加载更多完整实现源码
直接上代码 <template><view class"searchList"><!-- 搜索框 --><Search></Search><img class"top_img" src"/static/image/dataDelivery.png" /><view class"menus p_r"><view class&…

todoist 无法登陆_通过构建Todoist克隆将您的React技能提升到一个新的水平
todoist 无法登陆In this intermediate React course from Karl Hadwen, you will learn how to create the popular Todoist application from scratch using React, Custom Hooks, Firebase & the React Testing Library. You will lean how to use SCSS to style the ap…

w3cscholl的在线代码编辑工具
https://www.w3cschool.cn/tryrun/runcode?langc转载于:https://www.cnblogs.com/jhj117/p/7804133.html

点击事件加锁封装
看代码 // 提交答案 btnReply() {if (!this.$clickLock) returnthis.changeClickLock() } 封装代码 // 点击事件加锁 使用方式,在点击时加入以下代码// if (!this.$clickLock) return// this.changeClickLock()that.changeClickLock () > {that.$clickLock f…

WinCE 7 Mouse HOOK
WinCE 5.0&6.0 的鼠标 HOOK,偶在本博客中已经写过文章。WinCE7.0 的下的鼠标 HOOK 实现,完全和 WinCE 6 是一样的。 效果:在 WinCE 系统界面可以 HOOK 住鼠标的操作。 但是在 Silverlight 应用的界面,HOOK 功能失效。转载于:h…

devops和docker_通过免费的2小时Docker课程学习DevOps基础知识
devops和dockerDocker is a powerful DevOps tool for putting your apps into "containers." Docker是功能强大的DevOps工具,可将您的应用程序放入“容器”中。 You can run these same containers anywhere - on your laptop, on a server - even on a…

生成24位字符串ID__IdGenerator.java
此工具类用于生成24位字符串ID,唯一不重复。 直接通过 IdGenerator.get() 获取。 源码如下:(点击下载源码 - IdGenerator.java ) 1 import java.net.NetworkInterface;2 import java.nio.ByteBuffer;3 import java.nio.ByteOrder;4 import java.util.Enu…

IDEA构建一个mybatis项目
目录结构如下: 在pom.xml中配置需要的jar包 <dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.3.0</version></dependency><dependency><gro…

小程序在canvas上层做图片滚动
实现该功能踩过的坑 1.swiper的swiper-item中image图片无法在canvas的上层显示,会被canvas 覆盖 2.swiper的swiper-item 里面放 cover-image 会样式错乱 3.scroll-view里面放 cover-image 会样式错乱 解决方案:使用CSS样式实现,超出部分隐…

React是如何在后台运行的
React is a very popular JavaScript library. With over 5.5 million weekly downloads, React is enjoying great popularity. But not a lot of React developers know how React works under the hood. React是一个非常流行JavaScript库。 每周的下载量超过550万࿰…

H5播放视频流
代码 <html> <head> <title>视频直播</title> <meta charset"utf-8"> <link href"http://vjs.zencdn.net/5.5.3/video-js.css" rel"stylesheet"> <!-- If youd like to support IE8 --> <!-…

获取Java系统相关信息
1 package com.test;2 3 import java.util.Properties;4 import java.util.Map.Entry;5 6 import org.junit.Test;7 8 public class SystemTest {9 10 /** 11 * 获取Java系统相关信息 12 * throws Exception 13 */ 14 Test 15 public void testSys…

如何使用FaunaDB + GraphQL
I have one or two projects I maintain on Netlify, in addition to hosting my blog there. It’s an easy platform to deploy to, and has features for content management (CMS) and lambda functions (by way of AWS).除了在其中托管我的博客外,我在Netlify上…

POJ 1414 Life Line(搜索)
题意: 给定一块正三角形棋盘,然后给定一些棋子和空位,棋子序号为a(1<a<9),group的定义是相邻序号一样的棋子。 然后到C(1<N<9)棋手在空位放上自己序号C的棋子, 放完后&a…

MySQL_数据库操作语句
ZC:数据库名/表名/字段名 都使用小写字母 1、 创建 数据库 和 表 的时候,都要指定 编码方式为 utf-8 ! ! ! 因为 执行命令“show variables like char%;”后可以看到 character_set_database 的值为 latin1,即 默认创建数据库是使用的 字符编…

H5打开预览PDF,PPT等文件
实现代码: pdfUrl 写你的文件路径 <iframe :src"//www.xdocin.com/xdoc?_functo&_formathtml&_cache1&_xdocpdfUrl"width"100%"height"100%"frameborder"0"> </iframe> 可以直接打开看

广播代码_代码广播:专为编码而设计的24/7音乐
广播代码阅读本文时,您可以继续阅读Code Radio。 (You can go ahead and start listening to Code Radio while you read this) Most developers I know listen to music while they code. When the meetings are over, the headphones come out.我认识的大多数开发…

从 Android 静音看正确的查bug的姿势?
0、写在前面 没抢到小马哥的红包,无心回家了,回公司写篇文章安慰下自己TT。。话说年关难过,bug多多,时间久了难免头昏脑热,不辨朝暮,难识乾坤。。。艾玛,扯远了,话说谁没踩过坑&…

SecureCRT中sqlplus,使用Backspace删除时 ^H^H
在“Session Options” - "Terminal" - "Mapped Keys" - "Other mappings",选择“Backspace sends delete”。转载于:https://www.cnblogs.com/Clark-cloud-database/p/7813867.html

在vue中使用vuex,修改state的值示例
1、 安装 vuex npm install vuex -S 2、在目录下创建store文件 3、 在store.js编辑一个修改state的方法 然后在mian.js中全局引入 最后在组件中使用 这个的功能是运用mutations 修改state中的值

软件开发 自由职业_自由职业? 这里有7个可以出售软件开发服务的地方
软件开发 自由职业Web developers need clients. This is true whether you are a full-time freelancer or you freelance on the side.Web开发人员需要客户。 无论您是全职自由职业者,还是身旁的自由职业者,都是如此。 So if youve ever asked: "…

生成SSH key
1、打开终端,输入下面的代码 ,注意:$your_email为占位符,此处输入你自己的email ssh-keygen -t rsa -C "$your_email" 2、查看生成的公钥,输入下面的代码 cat ~/.ssh/id_rsa.pub 3、复制公钥(公钥…
[转载]二叉树(BST,AVT,RBT)
二叉查找树(Binary Search Tree)是满足如下性质的二叉树:①若它的左子树非空,则左子树上所有结点的值均小于根结点的值;②若它的右子树非空,则右子树上所有结点的值均大于根结点的值;③左、右子树本身又各是一棵二叉查…

Invalid Host header 问题解决
出现该问的原因: 因为新版的 webpack-dev-server 出于安全考虑,默认检查 hostname,如果hostname不是配置内的就不能访问。 解决办法:设置跳过host检查 打开你的项目全局搜索 devServer ,在 devServer 里面添加 &quo…

react hooks使用_为什么要使用React Hooks?
react hooks使用The first thing you should do whenever youre about to learn something new is ask yourself two questions -每当您要学习新东西时,应该做的第一件事就是问自己两个问题- Why does this thing exist? 为什么这东西存在? What probl…