Leo Jiang
Leo Jiang

Reputation: 26085

Lazy computed properties in Immutable.js Records?

Is there a standard way to define lazy computed properties on Records? When I access the computed property, it should run a function to compute the value, then cache the value. For example, something like:

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

The closest I can get is defining a getFullName() method, then manually memoizing the computed value. I.e.:

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

Upvotes: 1

Views: 250

Answers (1)

gforce301
gforce301

Reputation: 2984

As long as you don't need it to ever "re-compute" this should do it I think.

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

Upvotes: 1

Related Questions