在功能管道中使用ifElse(3分钟读取) 我们习惯于看这样的陈述
We’re used to seeing if statements like this

  1. const hasAccess = true;
  2. if (hasAccess) {
  3. console.log('Access granted.');
  4. } else {
  5. console.log('Access denied.');
  6. }

An increasingly popular alternative is the ternary statement.

  1. const hasAccess = true;
  2. const message = hasAccess ? 'Access granted.' : 'Access denied.';
  3. console.log(message);

Ramda provides ifElse, letting you handle branching logic with functions.

  1. import { ifElse } from 'ramda';
  2. const hasAccess = true;
  3. const logAccess = ifElse(
  4. () => hasAccess,
  5. () => console.log('Access granted.'),
  6. () => console.log('Access denied.')
  7. );
  8. 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变量,不如将其设为参数。

  1. import { ifElse } from 'ramda';
  2. const logAccess = ifElse(
  3. (hasAccess) => hasAccess,
  4. () => console.log('Access granted.'),
  5. () => console.log('Access denied.')
  6. );
  7. logAccess(true);

And instead of the console.log side-effect, purify it by simply returning your desired result.
而不是console.log的副作用,通过简单地返回您想要的结果来净化它。

  1. import { ifElse } from 'ramda';
  2. const logAccess = ifElse(
  3. (hasAccess) => hasAccess,
  4. () => 'Access granted.',
  5. () => 'Access denied.'
  6. );
  7. const result = logAccess(true);
  8. console.log({ result });

This makes a point-free style easier to achieve.
这使得无点样式更容易实现。

  1. import { always, equals, ifElse } from 'ramda';
  2. const logAccess = ifElse(
  3. equals(true),
  4. always('Access granted.'),
  5. always('Access denied.')
  6. );
  7. const result = logAccess(true);
  8. 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.

  1. const t = R.always('Tee');
  2. 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方法(如果存在)。

  1. R.equals(1, 1); //=> true
  2. R.equals(1, '1'); //=> false
  3. R.equals([1, 2, 3], [1, 2, 3]); //=> true
  4. const a = {}; a.v = a;//???
  5. const b = {}; b.v = b;//???
  6. R.equals(a, b); //=> true