Skip to content

Instantly share code, notes, and snippets.

@TGOlson
Created March 9, 2015 06:38
Show Gist options
  • Select an option

  • Save TGOlson/705580c9731d4bc17959 to your computer and use it in GitHub Desktop.

Select an option

Save TGOlson/705580c9731d4bc17959 to your computer and use it in GitHub Desktop.
Proxy JS
// `proxy` is a function to allow for point-free recursion in JavaScrpipt
// it takes in a function name as a string, and returns a proxy function to the original function
// examples
// explicit proxy - save proxy after declaration
// var length = ifElse(isEmpty, always(0), compose(inc, proxy('length'), tail));
// proxy('length', length);
// use short had proxy chaining
// var length = ifElse(isEmpty, always(0), compose(inc, proxy('length'), tail)).proxy('length');
// wrap declaration with proxy
// var length = proxy('length', ifElse(isEmpty, always(0), compose(inc, proxy('length'), tail)));
// invoke the proxy directly
// proxy('length', ifElse(isEmpty, always(0), compose(inc, proxy('length'), tail)));
// proxy('length')([1, 2, 3, 4])
var R = require('ramda');
var dropArgs = function(n) {
return R.compose(R.drop(2), getArgs);
};
var getArgs = function() {
return toArray(arguments);
};
var both = function(v1, v2) {
return v1 && v2;
};
var toArray = function(o) {
return Array.prototype.slice.call(o);
};
var proxies = {};
// Object -> String -> Function -> Function
var setProxy = R.partial(function(proxies, name, fn) {
proxies[name] = fn;
return fn;
}, proxies);
// Object -> String -> Function
var getProxy = R.partial(function(proxies, name) {
return R.partial(useProxy, proxies, name);
}, proxies);
// Object -> String -> IO
var throwProxyError = function(proxies, name) {
throw new Error('No established proxy for function: ' + name);
};
// Object -> String -> * -> *
var useProxy = R.ifElse(
R.propOf, R.converge(R.apply, R.propOf, dropArgs(2)), throwProxyError
);
// String, (Function) -> Function
var proxy = R.ifElse(both, setProxy, getProxy);
Function.prototype.proxy = function(name) {
return proxy(name, this);
};
module.exports = proxy;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment