Skip to content

Instantly share code, notes, and snippets.

@AlexeyRudkovskiy
Forked from creaux/Air.js
Created August 3, 2016 21:42
Show Gist options
  • Save AlexeyRudkovskiy/246bd180a1d508a8aa6831c9346399b4 to your computer and use it in GitHub Desktop.
Save AlexeyRudkovskiy/246bd180a1d508a8aa6831c9346399b4 to your computer and use it in GitHub Desktop.
Typescript Decorators
class Air {
@wetter
humidity;
}
export function WaterDefault(target) {
var original = target;
function construct(constructor, args) {
var c: any = function () {
return constructor.apply(this, args);
};
c.prototype = constructor.prototype;
return new c();
}
var f: any = function (...args) {
return construct(original, args);
};
f.prototype = original.prototype;
f.prototype.location = 'Prague';
f.prototype.koeficient = '50';
return f;
}
import twins from './twins';
export class Earth {
trees: [string];
constructor() {
this.trees = [];
}
@twins
public plant(seed) {
this.trees.push(seed);
}
}
// Method decorator
// is represented by three mandatory arguments
// first argument target represent function which is going to be decorated
// second argument key represent name of decorated method
// third argument value represent property descriptor
export function twins(target: Function, key: string, value: any) {
return {
value: function(...args:[]) {
var params = [];
params.push(args[0]);
params.push(args[0]);
var result = value.value.apply(this, params);
return result;
}
}
}
import { WaterDefault } from './decorators';
@WaterDefault
export default class Water {
hardness;
purity;
koeficient;
constructor() {
this.hardness = [ 'softer', 'soft', 'normal', 'hard', 'harder' ];
this.purity = {
'london': 'clean',
'prague': 'cleaner',
'berlin': 'suck'
}
}
public set location(value) {
this._location = value.toLowerCase();
}
public get location() {
return this._location;
}
public set koeficient(value) {
this._koeficient = value;
}
public get koeficient() {
return this._koeficient;
}
public quality() {
return [
this.purity[this.location],
return(this.hardness[Math.round((this.koeficient / 100) * (this.hardness.length - 1))]);
]
}
}
// wetter decorator
// target is prototype of decorated class
// key is the name of decorated class
export default function wetter(target, key) {
var _value = this[key];
function getter() {
return _value;
}
function setter(newValue) {
if(newValue <= 90) newValue += 10;
_value = newValue;
}
if(delete this[key]) {
Object.defineProperty(target, key, {
get: getter,
set: setter
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment