首页 > 解决方案 > 拉姆达或不拉姆达

问题描述

在团队中,我们试图决定是否应该ramda在我们的项目中使用。该项目在 Typesctipt 上,前面是 React,后面是 Nestjs。

目前,优缺点列表如下所示

优点:

  1. 代码很容易阅读
  2. 纯函数易于测试和重构

缺点:

  1. 如果您是 ramda 新手,很难阅读
  2. Ramda 的类型有问题,例如
interface Obj {p1: {p2: number}}

const obj: Obj = {
    p1: {
        p2: 1,
    }
}

const value = pathOr(null, ['p1', 'p2'], obj); //type of "value" will be "any"
  1. 与类一起使用ramda看起来很尴尬,例如
class Cl {
  method1() {...}

  method2() {...}

  method3() {
    return compose(
      this.method1.bind(this),
      this.method2.bind(this),
    )()
  }
}

很高兴看到对这些要点的任何考虑,或者添加更多的利弊。谢谢。

更新:

考虑到 geoffrey 的评论,当不可能不使用类时(比如在 NestJS 中),最好将 fp 样式的函数从类方法中分离出来,因为它们无论如何都是纯函数:

const method1Fn = () => {...};
const method2Fn = () => {...};
const method3Fn = () => compose(
  method1Fn,
  method2Fn,
)

class Cl {
  method3() {
    return method3Fn()
  }
}

甚至

class Cl {
  method3 = method3Fn
}

但在这种情况下,将为Cl.

标签: reactjsfunctional-programmingnestjsramda.js

解决方案


在这种情况下,可读性是使用问题。只要您将 Ramda 的用法保持在易于使用可读的地方,就不会成为问题。

此答案中的示例

这是非常可读的:

const siblings = me => reject(equals(me), family(me));

虽然这会过度使用 Ramda,并且可读性较差(并且可能需要手动类型):

const siblings = converge(reject, [unary(equals), family])

Ramda 的类型有问题,例如

虽然你可以安装@types/ramda推断是部分的。您可能会发现自己手动添加类型:

interface Obj {
  p1: { p2: number };
}

const obj: Obj = {
  p1: {
    p2: 1
  }
};

const fn: (obj: Obj) => null | number = pathOr(null, ['p1', 'p2']);

const value = fn(obj);

console.log(value);

将 ramda 与类一起使用看起来很尴尬,例如

您可以使用带有箭头函数的类属性来绑定方法,因此这实际上不是问题:

class Cl {
  method1 = () => {...}

  method2 = () => {...}

  method3() {
    return compose(
      this.method1,
      this.method2,
    )()
  }
}

推荐阅读