Skip to content

Commit

Permalink
refactor(util/lazy): Strict null check (#13455)
Browse files Browse the repository at this point in the history
* refactor(util/lazy): Strict null check

* Reimplement without `never` type cast

* Revert tsconfig.json

* Fix
  • Loading branch information
zharinov committed Jan 11, 2022
1 parent 895a85a commit 1d2c9d8
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 14 deletions.
44 changes: 30 additions & 14 deletions lib/util/lazy.ts
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;
}
}
2 changes: 2 additions & 0 deletions tsconfig.strict.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@
"lib/util/host-rules.ts",
"lib/util/html.ts",
"lib/util/http/**/.ts",
"lib/util/lazy.ts",
"lib/util/lazy.spec.ts",
"lib/util/index.ts",
"lib/util/json-writer/code-format.ts",
"lib/util/json-writer/editor-config.ts",
Expand Down

0 comments on commit 1d2c9d8

Please sign in to comment.