import _ from 'lodash' ; import * as Rx from 'rxjs' ; import { map } from 'rxjs/operators' ; import { IStorageWrapper } from 'src/plugins/opensearch_dashboards_utils/public' ; const defaultIsDuplicate = ( oldItem , newItem ) => { return _ . isEqual ( oldItem , newItem ) ; } ; interface PersistedLogOptions < T = any > { maxLength ? : number | string ; filterDuplicates ? : boolean ; isDuplicate ? : ( oldItem : T , newItem : T ) => boolean ; } export class PersistedLog < T = any > { public name : string ; public maxLength ? : number ; public filterDuplicates ? : boolean ; public isDuplicate : ( oldItem : T , newItem : T ) => boolean ; public storage : IStorageWrapper ; public items : T [ ] ; private update$ = new Rx . BehaviorSubject ( undefined ) ; constructor ( name , options = { } , storage ) { this . name = name ; this . maxLength = typeof options . maxLength === 'string' ? ( this . maxLength = parseInt ( options . maxLength , 10 ) ) : options . maxLength ; this . filterDuplicates = options . filterDuplicates || false ; this . isDuplicate = options . isDuplicate || defaultIsDuplicate ; this . storage = storage ; this . items = this . storage . get ( this . name ) || [ ] ; if ( this . maxLength !== undefined && ! isNaN ( this . maxLength ) ) { this . items = _ . take ( this . items , this . maxLength ) ; } } public add ( val ) { if ( val == null ) { return this . items ; } if ( this . filterDuplicates ) { _ . remove ( this . items , ( item ) => { return this . isDuplicate ( item , val ) ; } ) ; } this . items . unshift ( val ) ; if ( this . maxLength && ! isNaN ( this . maxLength ) ) { this . items = _ . take ( this . items , this . maxLength ) ; } this . storage . set ( this . name , this . items ) ; this . update$ . next ( undefined ) ; return this . items ; } public get ( ) { return _ . cloneDeep ( this . items ) ; } public get$ ( ) { return this . update$ . pipe ( map ( ( ) => this . get ( ) ) ) ; } }