# JavaScript Delegates w/ Currying Placeholders

A particularly powerful part of JavaScript is its vaguely functional aspects. However, they can at times be painful to use. The this name will rebind in surprising ways when passing around functions and there’s no native way to curry parameters, though you can of course form closures.

I’ve written a little library that gives something akin to std::bind from C++, but with the additional benefit of supporting the this context automatically.

The usage is pretty simple.

``````    delegate(obj, method)

delegate(this, this.method)

delegate(this, func);
``````

Nice and simple and about as obvious and concise as you can get. One could support passing a string as the second parameter to avoid needing to specify the object twice in some cases, I suppose, but then you’d like code completion and refactoring support in the editors that have them.

Once you have a delegate, you can call it like any function and it Just Works(tm). Arguments are forwarded on as expected, the return value is returned as expected, and so on.

But wait, I’ve also added currying! With this feature, you can bind extra parameters to the delegate itself so they’re automatically passed on. You can even use placeholders so you can mix in parameters to the delegate, change their order, or so on.

``````    // bind a binary function delegate but swap its inputs
delegate(func, bind(1), bind(0));

// bind a trinary function as a binary function with a curried parameter
delegate(func, bind(), "foo", bind());

// bind a unary function into one that takes 6 parameters and ignore the first 5
delegate(func, bind(5));
``````

I’ve found these all to be incredibly useful for event callbacks and the like while writing NodeJs code. In many cases I need to bind a callback to simply invoke some method with a static argument. In a few cases I need to support a mixture of static arguments and ones from the event callback. This delegate module lets me do all that!

There’s really not much to it:

``````    (function(){
function binder(n) { this.index = n; }
function bind(n) { return new binder(n); }

function delegate(obj, cb) {
if (arguments.length > 2) {
var curry = [].splice.call(arguments, 2);

var bound = false;
for (var i = 0; i < curry.length; ++i) {
if (curry[i] instanceof binder) {
bound = true;
break;
}
}

if (bound) {
return function(){
var params = [];
var next = 0;
for (var i = 0; i < curry.length; ++i) {
if (curry[i] instanceof binder) {
var index = curry[i].index;
if (index === undefined) {
params.push(arguments[next++]);
} else {
params.push(arguments[index]);
next = index + 1;
}
} else {
params.push(curry[i]);
}
}

return cb.apply(obj, params);
}
} else {
return function() { return cb.apply(obj, curry); }
}
} else {
return function(){ return cb.apply(obj, arguments); }
}
}

module.exports = delegate;
module.exports.delegate = delegate;
module.exports.bind = bind;
})();
``````

And here’s a little silly bit of test code to show how it works.

``````    var delegate = require('delegate')
, bind = delegate.bind;

var obj = {
a:1,
b: 'str',
m: function() { return this.b; },
d: function(v,u) { return this.a + v + u; }
};
function f(v,u) { return v + u; }

function call(cb) {
var params = [].splice.call(arguments, 1);
console.log(cb.apply(this, params));
}

call(delegate(obj, obj.m)); // prints str
call(delegate(obj, obj.d, 1, 2)); // prints 4
call(delegate(obj, obj.d, bind(), 4), 7); // prints 12
call(delegate(obj, obj.d, 4, bind(5)), 0, 1, 2, 3, 4, 5); // prints 10

var d = delegate(obj, obj.d, bind(), bind(3));

call(d, 7, 4, 5, 6); // prints 14

d = delegate(this, f, bind(1), bind(0));

call(f, "a", "n"); // prints ab
call(d, "a", "b"); // prints ba
``````

I note that the code could be made a slight bit prettier and more compact with the use of a helper library that extends Array with some useful methods, but I like the way the code right now has no extra module dependencies.
{"ft_lang_label":"__label__en","ft_lang_prob":0.69126177,"math_prob":0.9678596,"size":3931,"snap":"2021-31-2021-39","text_gpt3_token_len":993,"char_repetition_ratio":0.14540361,"word_repetition_ratio":0.037209302,"special_character_ratio":0.2905113,"punctuation_ratio":0.2049763,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9503296,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-09-22T01:56:20Z\",\"WARC-Record-ID\":\"<urn:uuid:042f4dcf-6eef-4796-9881-e5bb5146ca68>\",\"Content-Length\":\"20918\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:eb2884a7-a72c-406a-bc49-478e14b9c10f>\",\"WARC-Concurrent-To\":\"<urn:uuid:3801d6ba-29e6-4c6d-bb61-db9f60e68617>\",\"WARC-IP-Address\":\"185.199.110.153\",\"WARC-Target-URI\":\"https://seanmiddleditch.github.io/javascript-delegates-w-currying-placeholders/\",\"WARC-Payload-Digest\":\"sha1:5KHCHQ5R2367SIVU22A7MAFXEDH2SP7G\",\"WARC-Block-Digest\":\"sha1:3EYLDIFK6KNB3T73YOLTW76ZJ322NDTB\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-39/CC-MAIN-2021-39_segments_1631780057303.94_warc_CC-MAIN-20210922011746-20210922041746-00118.warc.gz\"}"}