如何在没有变异的情况下分配条件变量? [英] How do I assign a conditional variable without mutation?
问题描述
我坚持严格的函数式编程原则,没有变异。
I am adhering to strict functional programming principles with no mutation.
我怎样才能以不改变<$的方式编写类似下面代码的内容c $ c>问候变量,如果阻止,则不在每个内返回?
How can I write something like the below code in a way that doesn't mutate the greeting
variable, and without returning it within each if
block?
const greet = (name, time) => {
let greeting = 'Morning';
if(time >= 12) {
greeting = 'Afternoon';
}
if(time >= 17) {
greeting = 'Evening';
}
return `Good ${greeting} ${name}!`;
};
如果只是两个条件我会做以下事情,但是当它有时,它将不起作用3个条件:
If it was just two conditions I would do the following, but it won't work when there are 3 conditions:
const greeting = time > 12 ? 'Afternoon' : 'Morning'
推荐答案
三元表达式可以组成其他三元表达式 - 允许我们排序逻辑选择
Ternary expressions can be made up other ternary expressions – allowing us to sequence logical choices
const greeting = time > 12 ? (time > 17 ? 'Evening' : 'Afternoon') : 'Morning'
但是,我认为变量使变量成为变量 ...
However, I think it's the variable that makes the variable a variable...
您有两个担忧,并且它将使您分开它们将受益
You have two concerns though, and it it will benefit you to separate them
- 确定从小时开始的日期
- 组装问候语字符串
按这样做,你可以避免
- 变异(本地重新分配
问候语
) - 单分支如果语句
- 命令式风格的陈述(即
让
,if
,return
,x = ...
)
- mutation (local reassignment of
greeting
) - single-branch if statements
- imperative-style statements altogether (ie
let
,if
,return
,x = ...
)
结果是两个纯粹的( referentially transparent )使用表达式编写的函数 - 有没有任务(或重新分配),也没有副作用。
The result is two pure (referentially transparent) functions written using expressions – there is no assignment (or reassignment), and there are no side-effects.
const timeToPeriod = time =>
time >= 17
? 'Evening'
: time >= 12
? 'Afternoon'
: 'Morning'
const greet = (name, time) =>
`Good ${timeToPeriod(time)} ${name} !`
console.log(greet('Jonas', 9)) // Good Morning Jonas !
console.log(greet('Jonas', 13)) // Good Afternoon Jonas !
console.log(greet('Jonas', 22)) // Good Evening Jonas !
这篇关于如何在没有变异的情况下分配条件变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!