-
Notifications
You must be signed in to change notification settings - Fork 0
/
decorator.ts
53 lines (48 loc) · 1.48 KB
/
decorator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Defines the contract for a data source that can read and write data.
*/
interface DataSource {
readData(): string;
writeData(data: string): void;
}
/**
* Implements the `DataSource` interface by reading and writing data to a file.
*/
class FileDataSource implements DataSource {
private filename: string;
constructor(filename: string) {
this.filename = filename;
}
readData(): string {
return `Reading data from ${this.filename}`;
}
writeData(data: string): void {
console.log(`Writing data to ${this.filename}: ${data}`);
}
}
/**
* Decorator that measures the time it takes to read and write data using the wrapped `DataSource`.
* This decorator can be used to add performance measurement capabilities to any `DataSource` implementation.
*/
class DataSourceWithMeasureDecorator implements DataSource {
protected wrappee: DataSource;
constructor(source: DataSource) {
this.wrappee = source;
}
readData(): string {
const startTime = performance.now();
const result = this.wrappee.readData();
const endTime = performance.now();
const measure = endTime - startTime;
console.log(`Read time: ${measure} ms`);
return result;
}
writeData(data: string): void {
const startTime = performance.now();
this.wrappee.writeData(data);
const endTime = performance.now();
const measure = endTime - startTime;
console.log(`Write time: ${measure} ms`);
}
}
export { DataSource, DataSourceWithMeasureDecorator, FileDataSource };