import { Injectable , OnDestroy } from '@angular/core' ; import { AllocatedNode } from './api' ; @ Injectable ( { providedIn : 'root' } ) export class ObjectStore implements OnDestroy { private id = 0 ; private lookupByObject = new Map < AllocatedNode , number > ( ) ; private lookupById = new Map < number , AllocatedNode > ( ) ; allocateId ( ) { return this . id ++ ; } allocateNode ( element = new AllocatedNode ( ) , id = this . allocateId ( ) ) { this . store ( element , id ) ; return element ; } deallocateNode ( node ) { if ( this . lookupByObject . has ( node ) ) { const id = this . lookupByObject . get ( node ) ; this . lookupByObject . delete ( node ) ; this . lookupById . delete ( id ) ; } } store ( obj , id ) { this . lookupByObject . set ( obj , id ) ; this . lookupById . set ( id , obj ) ; } serialize ( obj ) { return this . lookupByObject . has ( obj ) ? this . lookupByObject . get ( obj ) : null ; } deserialize ( id ) { return this . lookupById . has ( id ) ? this . lookupById . get ( id ) : null ; } clear ( ) { this . lookupByObject . clear ( ) ; this . lookupById . clear ( ) ; } ngOnDestroy ( ) { this . clear ( ) ; } }