-
-
Notifications
You must be signed in to change notification settings - Fork 59
/
owning.ts
58 lines (45 loc) · 1.38 KB
/
owning.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
54
55
56
57
58
namespace $ {
export const $mol_owning_map = new WeakMap< any , any >()
export function $mol_owning_allow< Having >(
having : Having ,
) : having is Having & {
destructor() : void
} {
try {
if( !having ) return false
if( typeof having !== 'object' && typeof having !== 'function' ) return false
if( having instanceof $mol_delegate ) return false
if( typeof (having as any)['destructor'] !== 'function' ) return false
return true
} catch {
return false
}
}
export function $mol_owning_get< Having , Owner extends object >( having : Having , Owner? : { new() : Owner } ) : Owner | null {
if( !$mol_owning_allow( having ) ) return null
while( true ) {
const owner = $mol_owning_map.get( having )
if( !owner ) return owner
if( !Owner ) return owner
if( owner instanceof Owner ) return owner
having = owner
}
}
export function $mol_owning_check< Owner , Having >(
owner : Owner ,
having : Having ,
) : having is Having & { destructor() : void } {
if( !$mol_owning_allow( having ) ) return false
if( $mol_owning_map.get( having ) !== owner ) return false
return true
}
export function $mol_owning_catch< Owner , Having >(
owner : Owner ,
having : Having ,
) {
if( !$mol_owning_allow( having ) ) return false
if( $mol_owning_map.get( having ) ) return false
$mol_owning_map.set( having , owner )
return true
}
}