Skip to content

Instantly share code, notes, and snippets.

@shaoshing
Created March 29, 2015 15:23
Show Gist options
  • Save shaoshing/1899250ea22d83d82d0f to your computer and use it in GitHub Desktop.
Save shaoshing/1899250ea22d83d82d0f to your computer and use it in GitHub Desktop.
The Symmetry of JavaScript Functions (revised) http://raganwald.com/2015/03/12/symmetry.html
// Yellow - Decorator for method
function isFruit(name){
return ['banana', 'apple'].indexOf(name) !== -1;
}
function not(fn){
return function(){
return !fn.apply(null, arguments);
};
}
var names = ['banana', 'chestnut'];
names.filter(isFruit);
names.filter(not(isFruit));
// Blue - Decorator for Functions, aka Object.fn
function Tax(rate){
this.rate = rate;
}
Tax.prorotype.calculate = function(amount){
return amount*this.rate;
}
// this won't work for Tax.prototype.calculate
function requireNumberForMethod(fn){
return function(number){
if(!Number.isFinite(number)) throw number + ' is not a number';
return fn.apply(null, number);
}
}
function requireNumber(fn){
return function(number){
if(!Number.isFinite(number)) throw number + ' is not a number';
return fn.apply(this, number);
}
}
Tax.prototype.calculate = requireNumber(Tax.prototype.calculate);
tax = new Tax(0.8);
tax.calculate(100); //=> 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment