Created
March 29, 2015 15:23
-
-
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
This file contains 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
// 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