11'use strict' ;
22// This file is a modified version of the on-exit-leak-free module on npm.
33
4- const {
5- ArrayPrototypeFilter,
6- ArrayPrototypeIndexOf,
7- ArrayPrototypePush,
8- ArrayPrototypeSplice,
9- SafeFinalizationRegistry,
10- SafeWeakRef,
11- } = primordials ;
4+ const { SafeFinalizationRegistry, SafeSet, SafeWeakRef } = primordials ;
125const { validateObject, kValidateObjectAllowFunction } = require ( 'internal/validators' ) ;
136const { emitExperimentalWarning } = require ( 'internal/util' ) ;
147
@@ -20,8 +13,8 @@ function createFinalization() {
2013
2114 const refs = {
2215 __proto__ : null ,
23- exit : [ ] ,
24- beforeExit : [ ] ,
16+ exit : new SafeSet ( ) ,
17+ beforeExit : new SafeSet ( ) ,
2518 } ;
2619
2720 const functions = {
@@ -31,21 +24,21 @@ function createFinalization() {
3124 } ;
3225
3326 function install ( event ) {
34- if ( refs [ event ] . length > 0 ) {
27+ if ( refs [ event ] . size > 0 ) {
3528 return ;
3629 }
3730
3831 process . on ( event , functions [ event ] ) ;
3932 }
4033
4134 function uninstall ( event ) {
42- if ( refs [ event ] . length > 0 ) {
35+ if ( refs [ event ] . size > 0 ) {
4336 return ;
4437 }
4538
4639 process . removeListener ( event , functions [ event ] ) ;
4740
48- if ( refs . exit . length === 0 && refs . beforeExit . length === 0 ) {
41+ if ( refs . exit . size === 0 && refs . beforeExit . size === 0 ) {
4942 registry = null ;
5043 }
5144 }
@@ -70,14 +63,12 @@ function createFinalization() {
7063 fn ( obj , event ) ;
7164 }
7265 }
73- refs [ event ] = [ ] ;
66+ refs [ event ] . clear ( ) ;
7467 }
7568
7669 function clear ( ref ) {
7770 for ( const event of [ 'exit' , 'beforeExit' ] ) {
78- const index = ArrayPrototypeIndexOf ( refs [ event ] , ref ) ;
79- if ( index !== - 1 ) {
80- ArrayPrototypeSplice ( refs [ event ] , index , 1 ) ;
71+ if ( refs [ event ] . delete ( ref ) ) {
8172 uninstall ( event ) ;
8273 }
8374 }
@@ -92,7 +83,7 @@ function createFinalization() {
9283 registry ||= new SafeFinalizationRegistry ( clear ) ;
9384 registry . register ( obj , ref ) ;
9485
95- ArrayPrototypePush ( refs [ event ] , ref ) ;
86+ refs [ event ] . add ( ref ) ;
9687 }
9788
9889 /**
@@ -132,10 +123,12 @@ function createFinalization() {
132123 }
133124 registry . unregister ( obj ) ;
134125 for ( const event of [ 'exit' , 'beforeExit' ] ) {
135- refs [ event ] = ArrayPrototypeFilter ( refs [ event ] , ( ref ) => {
126+ for ( const ref of refs [ event ] ) {
136127 const _obj = ref . deref ( ) ;
137- return _obj && _obj !== obj ;
138- } ) ;
128+ if ( ! _obj || _obj === obj ) {
129+ refs [ event ] . delete ( ref ) ;
130+ }
131+ }
139132 uninstall ( event ) ;
140133 }
141134 }
0 commit comments