export default class DataMediator {
constructor ( ) {
this . store = new Map ( ) ;
}
notify ( sender, event, data = undefined ) {
let res;
if ( sender && event) {
switch ( event) {
case 'get' :
res = this . get ( sender) ;
break ;
case 'set' :
res = this . set ( sender, data) ;
break ;
default :
break ;
}
}
return res;
}
set ( sender, data) {
this . store. set ( sender, this . deepCopy ( data) ) ;
return this . store. get ( sender) ;
}
get ( sender) {
return this . store. get ( sender) ;
}
findFirst = ( list, f ) => list. filter ( f) [ 0 ]
deepCopy ( obj, cache = [ ] ) {
if ( obj === null || typeof obj !== 'object' ) {
return obj;
}
const hit = this . findFirst ( cache, ( c ) => c. original === obj) ;
if ( hit) {
return hit. copy;
}
const copy = Array. isArray ( obj) ? [ ] : { } ;
cache. push ( {
original: obj,
copy,
} ) ;
Object. keys ( obj) . forEach ( ( key ) => {
copy[ key] = this . deepCopy ( obj[ key] , cache) ;
} ) ;
return copy;
}
}
import DataMediator from '<path>/data_mediator' ;
function getTestValue ( ) {
return {
a: {
c: [ { e: 'e' , f: 'f' , g ( ) { return { m: 'm' } ; } } ] ,
d: 'd' ,
} ,
b: 'b' ,
} ;
}
describe ( 'data mediator class' , ( ) => {
it ( 'deepCopy' , ( ) => {
const dm = new DataMediator ( ) ;
const testValue = getTestValue ( ) ;
const gFun1 = testValue. a. c[ 0 ] . g;
const resFun1 = gFun1 ( ) ;
const testRes = dm. deepCopy ( testValue) ;
const gFun2 = testRes. a. c[ 0 ] . g;
const resFun2 = gFun2 ( ) ;
expect ( testValue === testRes) . toBe ( false ) ;
expect ( testRes) . toEqual ( testValue) ;
expect ( resFun1) . toEqual ( resFun2) ;
} ) ;
it ( 'notify' , ( ) => {
const dm = new DataMediator ( ) ;
const testValue = getTestValue ( ) ;
dm. notify ( 'test' , 'set' , testValue) ;
dm. notify ( 'test2' , 'set' , 'string' ) ;
expect ( dm. store instanceof Map ) . toBe ( true ) ;
expect ( dm. store. has ( 'test' ) ) . toBe ( true ) ;
expect ( dm. store. has ( 'test2' ) ) . toBe ( true ) ;
const resValue1 = dm. notify ( 'test' , 'get' ) ;
expect ( resValue1) . toEqual ( testValue) ;
expect ( resValue1 === testValue) . toBe ( false ) ;
const resValue2 = dm. notify ( 'test2' , 'get' ) ;
expect ( resValue2 === 'string' ) . toBe ( true ) ;
} ) ;
} ) ;