在功能管道中使用ifElse(3分钟读取) 我们习惯于看这样的陈述
We’re used to seeing if statements like this
const hasAccess = true;
if (hasAccess) {
console.log('Access granted.');
} else {
console.log('Access denied.');
}
An increasingly popular alternative is the ternary statement.
const hasAccess = true;
const message = hasAccess ? 'Access granted.' : 'Access denied.';
console.log(message);
Ramda provides ifElse, letting you handle branching logic with functions.
import { ifElse } from 'ramda';
const hasAccess = true;
const logAccess = ifElse(
() => hasAccess,
() => console.log('Access granted.'),
() => console.log('Access denied.')
);
logAccess();
One advantage is that you can package the logic away into a function. Instead of hardcoding the hasAccess variable, make it a parameter.
一个优点是可以将逻辑打包到函数中。与其硬编码hasAccess变量,不如将其设为参数。
import { ifElse } from 'ramda';
const logAccess = ifElse(
(hasAccess) => hasAccess,
() => console.log('Access granted.'),
() => console.log('Access denied.')
);
logAccess(true);
And instead of the console.log side-effect, purify it by simply returning your desired result.
而不是console.log的副作用,通过简单地返回您想要的结果来净化它。
import { ifElse } from 'ramda';
const logAccess = ifElse(
(hasAccess) => hasAccess,
() => 'Access granted.',
() => 'Access denied.'
);
const result = logAccess(true);
console.log({ result });
This makes a point-free style easier to achieve.
这使得无点样式更容易实现。
import { always, equals, ifElse } from 'ramda';
const logAccess = ifElse(
equals(true),
always('Access granted.'),
always('Access denied.')
);
const result = logAccess(true);
console.log({ result });
And the end result’s easier to test!
https://ramdajs.com/docs/#always
a → (* → a)
返回始终返回给定值的函数。请注意,对于非原语,返回的值是对原始值的引用。 此函数在其他语言和库中称为const、constant或K(对于K combinator)。
Parameters
Added in v0.1.0
Returns a function that always returns the given value. Note that for non-primitives the value returned is a reference to the original value.
This function is known as const, constant, or K (for K combinator) in other languages and libraries.
const t = R.always('Tee');
t(); //=> 'Tee'
https://ramdajs.com/docs/#equals
Returns true if its arguments are equivalent, false otherwise. Handles cyclical data structures.
Dispatches symmetrically to the equals methods of both arguments, if present.
如果参数相等,则返回true,否则返回false。处理循环数据结构。 对称地分派到两个参数的equals方法(如果存在)。
R.equals(1, 1); //=> true
R.equals(1, '1'); //=> false
R.equals([1, 2, 3], [1, 2, 3]); //=> true
const a = {}; a.v = a;//???
const b = {}; b.v = b;//???
R.equals(a, b); //=> true