// partial application
// is a way by which we can take a function and bind it against one or more parameters to create a new function
var op = $("#output");
op.append("Partial Application" + "<br/>");
Function.prototype.parApp = function() {
// capture the bound arguments
var args = Array.prototype.slice.call(arguments);
op.append("args: " + args + "<br/>");
var f = this;
// construct a new function
return function() {
// prepend argument list with the closed arguments from above
var inner_args = Array.prototype.slice.call(arguments);
op.append("inner_args: " + inner_args + "<br/>");
return f.apply(this, args.concat(inner_args))
};
};
var add = function(x, y) {
return x + y;
}
var add10 = add.parApp(10);
op.append(add10(5));
// composition
// composition is an operation that prduces a new function by nesting two functions
// z(x) = f(g(x))
op.append("<br/><br/>Composition<br/>");
Function.prototype.compo = function(g) {
var f = this;
return function() {
var args = Array.prototype.slice.call(arguments);
return f.call(this, g.apply(this, args));
};
};
var format1 = function(s) {
return "------------ " + s + " --------------";
};
var format2 = function(s) {
return "<< " + s + " >>";
};
var printWithFormat = format1.compo(format2);
op.append(printWithFormat("Some Text"));
// flipping
// convert function f(a,b) to g(b,a)
var div = function(a, b) {
return a / b;
};
op.append("<br/><br/>Flipping<br/>");
Function.prototype.flip = function() {
var f = this;
return function() {
var args = Array.prototype.slice.call(arguments);
return f.apply(this, args.reverse());
};
};
op.append(div(4, 2) + "<br/>");
op.append(div.flip()(4, 2) + "<br/>");
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.