Skip to content

Instantly share code, notes, and snippets.

@danharper
Created April 9, 2015 22:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danharper/ba41522516fc2adfb0a0 to your computer and use it in GitHub Desktop.
Save danharper/ba41522516fc2adfb0a0 to your computer and use it in GitHub Desktop.
ES7 Decorators
@ngInject('bus', '$ionicModal')
class Adder {
constructor(num) {
this.num = num
}
// order matters
// if you @swallow first, then @log won't log caught exceptions
@log
@swallow
@partial(100)
add(...numbers) {
if (numbers.includes(4)) throw new Error('I HATE 4')
return this.num + numbers.reduce((x,y) => x + y, 0)
}
}
console.log(Adder.$inject)
console.log((new Adder(10)).add(1, 2, 3))
console.log((new Adder(10)).add(4, 5, 6))
function ngInject(...deps) {
return function(declaration) {
declaration.$inject = deps
}
}
function log(target, name, descriptor) {
let fn = descriptor.value
descriptor.value = function(...args) {
console.log('Calling', name, 'with', args)
try {
let out = fn.apply(this, args)
console.log('Got', out)
return out
}
catch (e) {
console.log('Caught', e.message)
throw e
}
}
}
function swallow(t, n, descriptor) {
let fn = descriptor.value
descriptor.value = function(...args) {
try {
return fn.apply(this, args)
}
catch (e) {
return 'nothing happened ;)'
}
}
}
function partial(...partialArgs) {
return function(t, n, descriptor) {
let fn = descriptor.value
descriptor.value = function(...args) {
return fn.apply(this, [...partialArgs, ...args])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment