Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/copilot/src/util/vs/base/common/lazy.ts
13405 views
1
//!!! DO NOT modify, this file was COPIED from 'microsoft/vscode'
2
3
/*---------------------------------------------------------------------------------------------
4
* Copyright (c) Microsoft Corporation. All rights reserved.
5
* Licensed under the MIT License. See License.txt in the project root for license information.
6
*--------------------------------------------------------------------------------------------*/
7
8
enum LazyValueState {
9
Uninitialized,
10
Running,
11
Completed,
12
}
13
14
export class Lazy<T> {
15
16
private _state = LazyValueState.Uninitialized;
17
private _value?: T;
18
private _error: Error | undefined;
19
20
constructor(
21
private readonly executor: () => T,
22
) { }
23
24
/**
25
* True if the lazy value has been resolved.
26
*/
27
get hasValue(): boolean { return this._state === LazyValueState.Completed; }
28
29
/**
30
* Get the wrapped value.
31
*
32
* This will force evaluation of the lazy value if it has not been resolved yet. Lazy values are only
33
* resolved once. `getValue` will re-throw exceptions that are hit while resolving the value
34
*/
35
get value(): T {
36
if (this._state === LazyValueState.Uninitialized) {
37
this._state = LazyValueState.Running;
38
try {
39
this._value = this.executor();
40
} catch (err) {
41
this._error = err;
42
} finally {
43
this._state = LazyValueState.Completed;
44
}
45
} else if (this._state === LazyValueState.Running) {
46
throw new Error('Cannot read the value of a lazy that is being initialized');
47
}
48
49
if (this._error) {
50
throw this._error;
51
}
52
return this._value!;
53
}
54
55
/**
56
* Get the wrapped value without forcing evaluation.
57
*/
58
get rawValue(): T | undefined { return this._value; }
59
}
60
61