Skip to content

Instantly share code, notes, and snippets.

@deebloo
Last active September 16, 2016 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deebloo/a60b16411803ef53a06f626207d30282 to your computer and use it in GitHub Desktop.
Save deebloo/a60b16411803ef53a06f626207d30282 to your computer and use it in GitHub Desktop.
Compose function/decorator
// 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;
}
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')
}
}))
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