Created
April 9, 2015 22:15
-
-
Save danharper/ba41522516fc2adfb0a0 to your computer and use it in GitHub Desktop.
ES7 Decorators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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