Immutable.js 记录中的惰性计算属性?

Lazy computed properties in Immutable.js Records?

是否有一种标准方法可以在 Record 上定义惰性计算属性?当我访问计算 属性 时,它应该 运行 一个函数来计算值,然后缓存该值。例如,类似于:

const UserRecord = Record({
  firstName: '',
  lastName: '',
  get fullName() {
    console.log('Ran computation');
    return `${this.firstName} ${this.lastName}`;
  },
});

const user = new UserRecord({ firstName: 'Mark', lastName: 'Zuck' });
console.log(user.fullName); // Ran computation\nMark Zuck
console.log(user.fullName); // Mark Zuck

我能得到的最接近的是定义一个 getFullName() 方法,然后手动记忆计算值。即:

getFullName() {
  if (!this._fullName) {
    this._fullName = `${this.firstName} ${this.lastName}`;
  }
  return this._fullName;
}

只要你永远不需要它"re-compute"我认为这应该可以。

const UserRecord = Record({
  firstName: '',
  lastName: '',
  get fullName() {
    console.log('Ran computation');

    var value = `${this.firstName} ${this.lastName}`;

    delete this.fullName;

    Object.defineProperty(this, 'fullName', {
        value: value
    });

    return value;
  },
});

const user = new UserRecord({ firstName: 'Mark', lastName: 'Zuck' });
console.log(user.fullName); // Ran computation\nMark Zuck
console.log(user.fullName); // Mark Zuck