Skip to content

Instantly share code, notes, and snippets.

@frontdevops
Last active January 19, 2016 21:01
Show Gist options
  • Save frontdevops/25ccf18cb2fe782848ff to your computer and use it in GitHub Desktop.
Save frontdevops/25ccf18cb2fe782848ff to your computer and use it in GitHub Desktop.
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
* Base decorator for Coffee ingredients
* @param target
* @param cost
* @returns {any}
*/
function baseCoffeeIngredientDecorator(target, cost) {
// save a reference to the original constructor
var original = target;
// a utility function to generate instances of a class
function construct(constructor, args) {
var c = function () {
return constructor.apply(this, args);
};
c.prototype = constructor.prototype;
var ret = new c();
ret.cost += cost;
return ret;
}
// the new constructor behaviour
var f = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i - 0] = arguments[_i];
}
return construct(original, args);
};
// copy prototype so intanceof operator still works
f.prototype = original.prototype;
// return new constructor (will override original)
return f;
}
/**
* Decorator A
*/
function withMilk(target) {
return baseCoffeeIngredientDecorator(target, 0.5);
}
/**
* Decorator B
*/
function withWhip(target) {
return baseCoffeeIngredientDecorator(target, 0.7);
}
/**
* Decorator C
*/
function withSprinkles(target) {
return baseCoffeeIngredientDecorator(target, 0.2);
}
/**
* ConcreteComponent
* (class for decorate)
*/
var Coffee = (function () {
function Coffee() {
this.cost = 1;
}
Coffee.prototype.getCost = function () {
return this.cost;
};
Coffee = __decorate([
withMilk,
withWhip,
withSprinkles
], Coffee);
return Coffee;
})();
var myCoffee = new Coffee();
console.log(myCoffee.getCost());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment