Lazy load data on demand

by Dawid Ryłko

HTML

<!-- Leniwa memoizacja -->

<a href="https://dawidrylko.com/memoizacja-harry-potter-i-myslodsiewnia/" target="_blank">Leniwa memoizacja</a>

TypeScript

// 1. With placeholder element
class LazyValue<T> {
  private _value?: T;
  private hasBeenCalculated = false;
  
  constructor(private readonly calculation: () => T) {}
  
  public get value(): T {
    if (!this.hasBeenCalculated) {
      console.log(`📜 Activating the Marauder's Map for the first time...`);
      this._value = this.calculation();
      this.hasBeenCalculated = true;
    }
    return this._value!;
  }
}

const mapContent = new LazyValue(() => 'Hogwarts map with all secret passages');
console.log('The parchment lies closed.');
console.log(mapContent.value); // First use - calculation
console.log(mapContent.value); // Second use - instant return

// 2. With lazy function (thunk)
const createLazyFunction = <T>(calculation: () => T): () => T => {
  let value: T;
  let isCalculated = false;
  
  return () => {
    if (!isCalculated) {
      console.log('🔮 Looking into the crystal ball for the first time...');
      value = calculation();
      isCalculated = true;
    }
    return value;
  };
};

const getProphecy = createLazyFunction(() => 'THE ONE WITH THE POWER TO VANQUISH THE DARK LORD APPROACHES...');
console.log('The prophecy awaits discovery.');
console.log(getProphecy()); // First use - calculation
console.log(getProphecy()); // Second use - instant return