import _isFunction from 'lodash/isFunction' ; import _isEqual from 'lodash/isEqual' ; /**
 * 构建一对get set 方法
 * 用于在不同平台拥有统一方式调用体验
 */ export function buildRegFn < F extends ( ... args : any [ ] ) => any > ( name , defaultFunc ? ) { let func ; const get = ( ... args ) : ReturnType < F > => { if ( ! func ) { if ( _isFunction ( defaultFunc ) ) { return defaultFunc ( ... args ) ; } throw new Error ( `${ name } not regist` ) ; } return func ( ... args ) ; } ; const set = ( fn ) : void => { func = fn ; } ; return [ get , set ] as const ; } /**
 * 构建带事件监听的get set 方法
 */ export function buildRegFnWithEvent < F extends ( ... args : any [ ] ) => any > ( name , defaultFunc ? ) { const [ get , _set ] = buildRegFn ( name , defaultFunc ) ; const listenerList = [ ] ; const onSet = ( cb ) : void => { listenerList . push ( cb ) ; } ; const set = ( fn ) : void => { _set ( fn ) ; listenerList . forEach ( ( listener ) => listener ( fn ) ) ; } ; return [ get , set , onSet ] as const ; } /**
 * 缓存版本的buildRegFn
 */ export function buildCachedRegFn < F extends ( ... args : any ) => any > ( name , defaultFunc ? ) { const [ get , set ] = buildRegFn ( name , defaultFunc ) ; let _result = null ; let _lastArgs ; function isSame ( args ) { return _result !== null && _isEqual ( args , _lastArgs ) ; } const cachedGet = ( ... args ) => { if ( isSame ( args ) ) { return _result ; } else { const result = get ( ... args ) ; _result = result ?? null ; _lastArgs = args ; return result ; } } ; const refreshCache = ( ) => { _result = null ; } ; const cachedSet = ( fn ) => { set ( fn ) ; refreshCache ( ) ; } ; return [ cachedGet , cachedSet , refreshCache ] ; } /**
 * 缓存版本的buildRegFn
 * Promise 版本
 */ export function buildCachedRegFnAsync < F extends ( ... args : any ) => any > ( name , defaultFunc ? ) { const [ get , set ] = buildRegFn ( name , defaultFunc ) ; let _result = null ; let _lastArgs ; function isSame ( args ) { return _result !== null && _isEqual ( args , _lastArgs ) ; } const cachedGet = async ( ... args ) => { if ( isSame ( args ) ) { return _result ; } else { const result = await get ( ... args ) ; _result = result ?? null ; _lastArgs = args ; return result ; } } ; const refreshCache = ( ) => { _result = null ; } ; const cachedSet = ( fn ) => { set ( fn ) ; refreshCache ( ) ; } ; return [ cachedGet , cachedSet , refreshCache ] ; }