首页 > 其他分享 >[Typescript] Builder pattern - 05 Exercise

[Typescript] Builder pattern - 05 Exercise

时间:2023-03-11 22:55:21浏览次数:41  
标签:map Typescript methodName log ... pattern Builder console any

class Overriden<TMap extends object = {}> {
  private map: TMap;

  constructor(obj: TMap) {
    this.map = obj;
  }

  build() {
    return this.map
  }

  method<TMethodName extends (keyof TMap) & string, TListener extends (copyFn: TMap[TMethodName], ...args: any[]) => void>(
    methodName: TMethodName, listener: TListener
  ):  Overriden<TMap & Record<TMethodName, TListener>> {
    if (typeof this.map[methodName] !== 'function') {
      throw new Error(`${methodName} not a function`)
    }
    if ((this.map[methodName] as any)['__overriden__']) {
      console.warn(`${methodName} got overriden already`)
      return this as any;
    }
    const copyFn = this.map[methodName];
    (this.map as any)[methodName] = (...args: any[]) => {
      listener.call(this.map, copyFn, ...args);
    }
    (this.map[methodName] as any)['__overriden__'] = true
    return this as any;
  }
}

const win = {
  close() {
    console.log('close is called') // you won't see this
  },
  open(...args: any[]) {
    console.log('open is called', ...args)
  },
  other() {
    console.log('other is called')
  },
  isObj: true
}
const overriden = new Overriden(win)

const win2 = overriden
.method('close', (copyFn) => {
 console.log('closed is overrided')
}).method('open', (copyFn, ...args) => {
  console.log('open is overrided')
   copyFn(...args)
}).build()

win2.close()
win2.open()
win2.other()
console.log(win2.isObj)

 

标签:map,Typescript,methodName,log,...,pattern,Builder,console,any
From: https://www.cnblogs.com/Answer1215/p/17207289.html

相关文章