-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(util/lazy): Strict null check (#13455)
* refactor(util/lazy): Strict null check * Reimplement without `never` type cast * Revert tsconfig.json * Fix
- Loading branch information
Showing
2 changed files
with
32 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,43 @@ | ||
interface ValueResult<T> { | ||
type: 'success'; | ||
value: T; | ||
} | ||
|
||
interface ErrorResult { | ||
type: 'error'; | ||
err: Error; | ||
} | ||
|
||
export class Lazy<T> { | ||
private _didRun = false; | ||
private _value?: T; | ||
private _error: Error | undefined; | ||
private _result?: ValueResult<T> | ErrorResult; | ||
|
||
constructor(private readonly executor: () => T) {} | ||
|
||
hasValue(): boolean { | ||
return this._didRun; | ||
return !!this._result; | ||
} | ||
|
||
getValue(): T { | ||
if (!this._didRun) { | ||
try { | ||
this._value = this.executor(); | ||
} catch (err) { | ||
this._error = err; | ||
} finally { | ||
this._didRun = true; | ||
const result = this._result; | ||
if (result) { | ||
if (result.type === 'success') { | ||
return result.value; | ||
} | ||
|
||
throw result.err; | ||
} | ||
if (this._error) { | ||
throw this._error; | ||
|
||
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; | ||
} | ||
return this._value; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters