Last active
September 16, 2016 21:41
-
-
Save deebloo/a60b16411803ef53a06f626207d30282 to your computer and use it in GitHub Desktop.
Compose function/decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Our compose function that can be used as a decorator | |
// Decorators are just functions | |
const Compose = (mixins: any[]) => { | |
const protos = mixins.map(mixin => mixin.prototype) | |
const targetFunc = target => { | |
Object.assign(target.prototype, ...protos) | |
} | |
targetFunc.create = (base: any) =>{ | |
const proto = Object.assign({}, base, ...protos); | |
const newObj = Object.create(proto); | |
if(newObj.init) { | |
newObj.init() | |
} | |
return newObj; | |
} | |
return targetFunc; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Compose } from './compose'; | |
import { CanTalk, CanMarch, CanShoot } from './props'; | |
// Sniper Class w/ Decorator | |
@Compose([CanTalk, CanMarch, CanShoot]) | |
class Sniper { | |
goProne() { | |
console.log('Go Prone') | |
} | |
} | |
const sniper1 = new Sniper(); | |
const sniperFactory = Compose([CanTalk, CanMarch, CanShoot]); | |
const sniper2 = sniper.create({ | |
goProne() { | |
console.log('Go Prone') | |
} | |
})) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class CanTalk { | |
talk() { | |
console.log('Hello'); | |
} | |
} | |
export class CanMarch { | |
march() { | |
console.log('MARCH!') | |
} | |
} | |
export class CanShoot { | |
shoot() { | |
cosole.log('shoot!!!') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment