Last active
September 20, 2016 15:09
-
-
Save gilbert/13d4593b00b4ee7cea33 to your computer and use it in GitHub Desktop.
JavaScript Function Extensions
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
| // Curry a function. Useful for binding specific data | |
| // to an event handler. | |
| // Example: | |
| // | |
| // var add = function (x,y) { return x + y; } | |
| // var add5 = add.curry(5) | |
| // add5(7) //=> 11 | |
| // | |
| Function.prototype.curry = function () { | |
| var slice = Array.prototype.slice | |
| var fn = this | |
| var args = slice.call(arguments) | |
| return function () { | |
| return fn.apply(this, args.concat(slice.call(arguments))) | |
| } | |
| } | |
| // Simply prevent the default action. Useful for preventing | |
| // anchor click page jumps and form submits. | |
| // Example: | |
| // | |
| // var x = 0; | |
| // var increment = function () { x += 1 } | |
| // myAnchorEl.addEventListener('click', increment.chill()) | |
| // | |
| Function.prototype.chill = function() { | |
| var fn = this | |
| return function(e) { | |
| e.preventDefault() | |
| return fn() | |
| }; | |
| }; | |
| // Both prevent default and curry in one go | |
| // Example: | |
| // | |
| // var x = 0; | |
| // var increment = function (amount) { x += amount } | |
| // myAnchorEl.addEventListener('click', increment.coldCurry(17)) | |
| // | |
| Function.prototype.coldCurry = function() { | |
| var slice = Array.prototype.slice | |
| var fn = this | |
| var args = slice.call(arguments) | |
| return function(e) { | |
| e.preventDefault() | |
| return fn.apply(this, args.concat(slice.call(arguments, 1))) | |
| }; | |
| }; | |
| // Compose two functions together, | |
| // piping the result of one to the other. | |
| // Example: | |
| // | |
| // var double = function (x) { return x * 2 } | |
| // var addOne = function (x) { return x + 1 } | |
| // var doublePlus = double.andThen(addOne) | |
| // doublePlus(3) //=> 7 | |
| // | |
| Function.prototype.andThen = function(f) { | |
| var g = this | |
| return function() { | |
| var slice = Array.prototype.slice | |
| var args = slice.call(arguments) | |
| return f.call(this, g.apply(this, args)) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very useful functions, but check your maths: 5 +7 = 12!! in the description of papp
add5(7) //=> 11