1
- import { Notify } from "./notify.ts" ;
2
-
3
1
/**
4
2
* A stack implementation that allows for adding and removing elements, with optional waiting when
5
3
* popping elements from an empty stack.
@@ -20,7 +18,7 @@ import { Notify } from "./notify.ts";
20
18
* @template T The type of items in the stack.
21
19
*/
22
20
export class Stack < T extends NonNullable < unknown > | null > {
23
- #notify = new Notify ( ) ;
21
+ #resolves: ( ( ) => void ) [ ] = [ ] ;
24
22
#items: T [ ] = [ ] ;
25
23
26
24
/**
@@ -34,7 +32,7 @@ export class Stack<T extends NonNullable<unknown> | null> {
34
32
* Returns true if the stack is currently locked.
35
33
*/
36
34
get locked ( ) : boolean {
37
- return this . #notify . waiterCount > 0 ;
35
+ return this . #resolves . length > 0 ;
38
36
}
39
37
40
38
/**
@@ -44,7 +42,7 @@ export class Stack<T extends NonNullable<unknown> | null> {
44
42
*/
45
43
push ( value : T ) : void {
46
44
this . #items. push ( value ) ;
47
- this . #notify . notify ( ) ;
45
+ this . #resolves . shift ( ) ?. ( ) ;
48
46
}
49
47
50
48
/**
@@ -59,7 +57,12 @@ export class Stack<T extends NonNullable<unknown> | null> {
59
57
if ( value !== undefined ) {
60
58
return value ;
61
59
}
62
- await this . #notify. notified ( { signal } ) ;
60
+ const { promise, resolve, reject } = Promise . withResolvers < void > ( ) ;
61
+ signal ?. addEventListener ( "abort" , ( ) => reject ( signal . reason ) , {
62
+ once : true ,
63
+ } ) ;
64
+ this . #resolves. push ( resolve ) ;
65
+ await promise ;
63
66
}
64
67
}
65
68
}
0 commit comments