Skip to content

Commit

Permalink
feat: add applyMixins util
Browse files Browse the repository at this point in the history
  • Loading branch information
bubkoo committed Dec 4, 2019
1 parent cee7071 commit f560a5d
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
32 changes: 31 additions & 1 deletion packages/x6/src/util/function.test.ts
@@ -1,7 +1,37 @@
import sinon from 'sinon'
import { call, apply, once, cacher } from './function'
import { applyMixins, call, apply, once, cacher } from './function'

describe('function', () => {
describe('#applyMixins', () => {
class Disposable {
isDisposed: boolean
dispose() {
this.isDisposed = true
}
}

class Activatable {
protected isActive: boolean
activate() {
this.isActive = true
}
deactivate() {
this.isActive = false
}
}

class SmartObject {}

interface SmartObject extends Disposable, Activatable {}
applyMixins(SmartObject, [Disposable, Activatable])

const instance = new SmartObject()

expect(instance.isDisposed).toBeFalsy()
instance.dispose()
expect(instance.isDisposed).toBeTruthy()
})

describe('#call', () => {
it('should invoke function with empty args', () => {
const spy = sinon.spy()
Expand Down
18 changes: 15 additions & 3 deletions packages/x6/src/util/function.ts
@@ -1,9 +1,21 @@
import { isFunction } from './lang'

export function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
Object.defineProperty(
derivedCtor.prototype,
name,
Object.getOwnPropertyDescriptor(baseCtor.prototype, name)!,
)
})
})
}

export function invoke<T>(
func: ((...args: any[]) => T) | null | undefined,
args: any[],
ctx: any
ctx: any,
): T {
let ret

Expand Down Expand Up @@ -36,7 +48,7 @@ export function invoke<T>(
export function apply<T>(
func: ((...args: any[]) => T) | null | undefined,
ctx: any,
args: any[] = []
args: any[] = [],
): T {
return invoke(func, args, ctx)
}
Expand All @@ -60,7 +72,7 @@ function repush<T>(array: T[], item: T) {
export function cacher<T extends Function>(
fn: T,
ctx?: any,
postProcessor?: (v: any, hasCache?: boolean) => any
postProcessor?: (v: any, hasCache?: boolean) => any,
): T {
const keys: string[] = []
const cache: { [kry: string]: any } = {}
Expand Down

0 comments on commit f560a5d

Please sign in to comment.