Skip to content
Snippets Groups Projects
Select Git revision
  • 99f01dbe708a16630b14b39afd80767aab0daac4
  • master default protected
  • v1.13.0
  • v1.12.0
  • v1.11.0
  • v1.10.0
  • v1.9.0
  • v1.8.0
  • v1.7.0
  • v1.6.0
  • v1.5.0
  • v1.4.0
  • v1.3.1
  • v1.3.0
  • v1.2.0
  • v1.1.1
  • v1.1.0
  • v1.0.2
  • v1.0.1
  • v1.0.0
20 results

README.md

Blame
  • lazy.ts 757 B
    interface ValueResult<T> {
      type: 'success';
      value: T;
    }
    
    interface ErrorResult {
      type: 'error';
      err: Error;
    }
    
    export class Lazy<T> {
      private _result?: ValueResult<T> | ErrorResult;
    
      constructor(private readonly executor: () => T) {}
    
      hasValue(): boolean {
        return !!this._result;
      }
    
      getValue(): T {
        const result = this._result;
        if (result) {
          if (result.type === 'success') {
            return result.value;
          }
    
          throw result.err;
        }
    
        return this.realizeValue();
      }
    
      private realizeValue(): T {
        try {
          const value = this.executor();
          this._result = { type: 'success', value };
          return value;
        } catch (err) {
          this._result = { type: 'error', err };
          throw err;
        }
      }
    }