Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Debug/Checked compilation
const DEBUG = true;
function conditional(condition) {
return target => condition ? target : Function.prototype;
}
@conditional(DEBUG)
function assert(condition, message = "assertion failed.") {
if (!condition) throw new Error(message);
}
// Conditional decorators
@conditional(TRACE)
function log(message) {
return target => function () {
console.log(message);
return target.apply(this, arguments);
};
}
@log("entering main()") // only when TRACE is true
function main() { }
// Design-time metadata
@metadata("design:paramtypes", () => [Number, Number])
@metadata("design:returntype", () => Number)
function add(a, b) {
return a + b;
}
// Testing
@test function addIsCorrect() {
const a = 1, b = 1;
const expected = 2;
let result = add(a, b);
assert(result === expected);
}
// API deprecation
function obsolete(message, isError) {
return target => function () {
if (isError) throw new Error(message);
console.warn(message);
return target.apply(this, arguments);
};
}
@obsolete("This API is obsolete and will be removed in v2")
export function oldAPIFunction() {
}
// Dependency Injection/IoC
import { WidgetFactory, PartBuilder, Fabricator } from "service-symbols";
@parameter(0, inject(PartBuilder))
@parameter(1, inject(Fabricator))
function widgetFactory(partBuilder, fabricator) {
return fabricator.fabricate(partBuilder.build());
}
const container = new DIContainer();
container
.for(PartBuilder).use(concretePartBuilder)
.for(Fabricator).use(concreteFabricator)
.for(WidgetFactory).use(widgetFactory)
let factory = container.get(WidgetFactory);
let widget = factory();
// Diagnostics/Performance
@measure("parse")
@log({ category: "parse" })
function parse(tokens) {
// ...
}
@measure("emit")
@log({ category: "emit" })
function emit(ast, out) {
// ...
}
// ...
console.log("parse time: " + measure.for("parse"));
console.log("emit time: " + measure.for("emit"));
// Others/Future extensibility...
@futurePrototocolOnTopOfGenerators function* fancy() {}
@curryify function add(a, b) { }
@pure function f() { }
@permission("unrestricted") function accessLocker() { }
@operator(Point, "+", Point) function addPointAndPoint(p1, p2) { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.