如何在JavaScript中使用when()有条件地更改值
30 Seconds of Code is a brilliant collection of JavaScript snippets, digestible in ≤ 30 seconds. Anyone looking to master JavaScript should go through the entire thing.
30秒的代码是精妙JavaScript片段集合,可在≤30秒内消化。 任何想要精通JavaScript的人都应该仔细研究整个过程。
Inspired by Ramda, I contributed when()
to 30secondsofcode’s official GitHub repo. This is one my favorite functions.
受Ramda的启发,我将when()
贡献给30secondsofcode的官方GitHub存储库 。 这是我最喜欢的功能之一。
when()
takes 3 parameters:
when()
采用3个参数:
pred
: A predicate function (must returntrue
orfalse
)pred
:谓词函数(必须返回true
或false
)whenTrue
: A function to run ifpred
returnstrue
.whenTrue
:如果pred
返回true
运行的函数。A value:
x
.值:
x
。
Here’s the most basic implementation:
这是最基本的实现:
when = (pred, whenTrue, x) => {if (pred(x)) {return whenTrue(x);} else {return x;}
};
Which you can shorten to:
您可以将其缩短为:
when = (pred, whenTrue, x) => (pred(x) ? whenTrue(x) : x);
Let’s say we want to triple even numbers
假设我们想将偶数增加三倍
when((x) => x % 2 === 0, (x) => x * 3, 2);
// 6
We got 6
because 2
is an even number. What if we pass 11
?
我们得到6
是因为2
是偶数。 如果我们通过11
怎么办?
when((x) => x % 2 === 0, (x) => x * 3, 11);
// 11
更进一步 (A Step Further)
when
currently needs all 3 parameters at once–what if we could supply just the first 2, and give x
later on?
当前when
需要同时使用所有3个参数-如果我们可以仅提供前两个参数,然后再给出x
,该怎么办?
when = (pred, whenTrue) => (x) => (pred(x) ? whenTrue(x) : x);
This version’s what I submitted to 30secondsofcode.org. Now our code’s more flexible.
这个版本是我提交给30secondsofcode.org的版本 。 现在我们的代码更加灵活。
tripleEvenNums = when((x) => x % 2 === 0, (x) => x * 3);tripleEvenNums(20); // 60
tripleEvenNums(21); // 21
tripleEvenNums(22); // 66
甚至更远 (Even Further Beyond)
We can pass x
later because when(pred, whenTrue)
returns a function expecting x
. What if we curry when()
?
我们可以稍后传递x
因为when(pred, whenTrue)
返回一个期望x
的函数。 如果我们咖喱when()
怎么办?
If you’re new to currying see my article on it.
如果您是新手,请参阅我的文章 。
A curried function doesn’t need all its parameters at once. You can supply some and get a function that takes the rest, allowing for powerful patterns.
咖喱函数不需要一次所有的参数。 您可以提供一些功能,并获得剩下的功能,以实现强大的模式。
一个愚蠢的例子 (A Silly Example)
Imagine we have two lists of people, both contain a guy named Bobo
.
想象一下,我们有两个人名单,每个人都包含一个名叫Bobo
。
Bobo
wants a nickname for each list.
Bobo
希望为每个列表起一个昵称。
If we find
Bobo
in list 1, change his name toB Money
.如果我们在列表1中找到
Bobo
,Bobo
他的名字更改为B Money
。If we find
Bobo
in list 2, change his name toBo-bob
.如果我们在列表2中找到
Bobo
,Bobo
其名称更改为Bo-bob
。
Currying when
allows us to easily write a function for each concern.
Curing when
允许我们轻松地为每个关注点编写一个函数。
If you’re following along, here’s a curry
function from 30secondsofcode.org.
如果您正在遵循,这里是30secondsofcode.org中的curry
函数。
curry = (fn, arity = fn.length, ...args) =>arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
We’ll need a predicate to find Bobo
.
我们需要一个谓词才能找到Bobo
。
isBobo = (person) => person.name === 'Bobo';
To keep our functions pure, we’ll need a way to immutably change a person’s name.
为了保持功能纯净,我们需要一种不变地更改人名的方法。
changeName = (newName, obj) => ({...obj,name: newName
});
Let’s also curry it so we can supply just newName
.
我们还要对其进行咖喱处理,以便仅提供newName
。
changeName = curry((newName, obj) => ({...obj,name: newName
}));
Here’s our lists.
这是我们的清单。
list1 = [{name: 'Bobo',id: 1,iq: 9001},{name: 'Jaime',id: 2,iq: 9000},{name: 'Derek',id: 3,iq: 8999}
];list2 = [{name: 'Sam',id: 1,iq: 600},{name: 'Bobo',id: 2,iq: 9001},{name: 'Peter',id: 3,iq: 8}
];
Let’s map over list1
.
让我们映射到list1
。
doIfBobo = when(isBobo);
renameToBMoney = changeName('B Money');list1.map(doIfBobo(renameToBMoney));
Our result:
我们的结果:
[{name: 'B Money',id: 1,iq: 9001},{name: 'Jaime',id: 2,iq: 9000},{name: 'Derek',id: 3,iq: 8999}
];
Because of when
, we only changed Bobo
and ignored everyone else!
由于when
,我们只换了Bobo
而忽略了其他所有人!
Now map over list2
.
现在映射到list2
。
renameToBoBob = changeName('Bo-bob');list2.map(doIfBobo(renameToBoBob));
Our result:[{"name": "Sam","id": 1,"iq": 600
},{"name": "Bo-bob","id": 2,"iq": 9001**},{"name": "Peter","id": 3,"iq": 8}
];
Looks good to me! We gave Bobo
his nicknames without affecting anyone else.
在我看来很好! 我们给了Bobo
他的昵称,却没有影响到其他人。
If you’re further interested, consider these links:
如果您进一步感兴趣,请考虑以下链接:
30secondsofcode.org’s collection
30secondsofcode.org的收藏
My article on currying
我关于currying的文章
Ramda
拉姆达
翻译自: https://www.freecodecamp.org/news/30-seconds-of-code-conditionally-change-values-with-when-732b09e46334/
如何在JavaScript中使用when()有条件地更改值相关推荐
- javascript编写_如何在JavaScript中使用解构来编写更简洁,功能更强大的代码
javascript编写 by Ashay Mandwarya ?️?? 由Ashay Mandwarya提供吗? 如何在JavaScript中使用解构来编写更简洁,功能更强大的代码 (How to ...
- 如何在javascript中使用多个分隔符分割字符串?
如何在JavaScript中使用多个分隔符拆分字符串? 我正在尝试在逗号和空格上进行拆分,但是AFAIK,JS的拆分功能仅支持一个分隔符. #1楼 对于那些想要在拆分功能中进行更多自定义的人,我编写了 ...
- 如何在JavaScript中直观地设计状态
by Shawn McKay 肖恩·麦凯(Shawn McKay) 如何在JavaScript中直观地设计状态 (How to visually design state in JavaScript) ...
- 我如何在JavaScript中建立良好的发布过程
by Dafna Rosenblum 达夫娜·罗森布拉姆(Dafna Rosenblum) 我如何在JavaScript中建立良好的发布过程 (How I established a good rel ...
- 如何在JavaScript中实现链接列表
If you are learning data structures, a linked list is one data structure you should know. If you do ...
- regexp 好汉字符串_如何在JavaScript中使用RegExp确认字符串的结尾
regexp 好汉字符串 by Catherine Vassant (aka Codingk8) 由凯瑟琳·瓦森(Catherine Vassant)(又名Codingk8) 如何在JavaScrip ...
- !! javascript_产量! 产量! 生成器如何在JavaScript中工作。
!! javascript by Ashay Mandwarya ?️?? 由Ashay Mandwarya提供吗? 产量! 产量! 生成器如何在JavaScript中工作. (Yield! Yiel ...
- javascript案例_如何在JavaScript中使用增强现实-一个案例研究
javascript案例 by Apurav Chauhan 通过Apurav Chauhan 如何在JavaScript中使用增强现实-一个案例研究 (How to use Augmented Re ...
- java+script+当前日期_如何在JavaScript中获取当前日期?
如何在JavaScript中获取当前日期? #1楼 您可以使用扩展了 Date对象的Date.js库,从而可以使用.today()方法. #2楼 如果您想对日期格式进行更多的粒度控制,我强烈建议您查看 ...
- 如何在Javascript中访问对象的第一个属性?
本文翻译自:How to access the first property of an object in Javascript? Is there an elegant way to access ...
最新文章
- 新书推荐:《追问人工智能:从剑桥到北京》
- latex二元关系符号
- PHP中Foreach在引用时的陷阱
- Javascript ES6 Promise异步链式读取文件解决回调地狱
- Androidstudio抽取成员变量快捷键 快捷键大全 自定义setting文件
- 代码块作用域内外的静态变量
- Java 网络编程之Socket详解
- 最最简单的几个Mac终端命令
- 手心拼音输入法 v1.0 官方版
- 【笔记】一些Attention 方面的网络
- 许可协议html,许可协议
- 两个方法做APP界面展示图片
- ppt中的流程图怎么整体移动_PPT中绘流程图
- vue自定义点击空白隐藏其他标签
- java 过滤字符串_java 过滤字符串方法实现
- python代码做图_如何用Python代码制作图
- Web前端开发是做什么的?学Web前端有前途吗?
- fadeIn()与fadeOut()方法
- JS常用代码片段-127个常用罗列-值得收藏
- Emojis should be wrapped in <span>, have role=“img“, and have an accessible description with aria-la