import Hash from "./Hash" ; export type Listener < T > = ( key : any , value : T ) => any ; export default class Cache < T > { enabled : boolean = true ; values : Hash < T > = { } ; changeListeners : Listener < T > [ ] = [ ] ; destroyListeners : Listener < T > [ ] = [ ] ; get ( key ) { return this . values [ key ] ; } set ( key , value ) { if ( this . enabled ) { this . values [ key ] = value ; this . emitChange ( key , value ) ; } return value ; } destroy ( key ) { if ( this . enabled && typeof this . values [ key ] !== "undefined" ) { delete this . values [ key ] ; this . emitDestroy ( key ) ; } } clear ( ) { this . values = { } ; } onChange ( callback ) { this . changeListeners . push ( callback ) ; } protected emitChange ( key , value ) { this . changeListeners . forEach ( ( callback ) => callback ( key , value ) ) ; } onDestroy ( callback ) { this . destroyListeners . push ( callback ) ; } protected emitDestroy ( key ) { this . destroyListeners . forEach ( ( callback ) => callback ( key ) ) ; } }