Lisp-style Generic Functions in Javascript October 28th, 2013
Patrick Stein

I have been spending some time over at codewars.com. It is an interactive platform where you can train on Javascript, Coffeescript, or Ruby exercises. The other participants in the site add their own exercises.

I just added an exercise to implement Lisp-style Generic Functions (including the standard method combinations) in Javascript. I’m pretty happy with the way my code came out.

var append = defgeneric('append');
append.defmethod('Array,Array', function (a,b) { return a.concat(b); });
append.defmethod('*,Array', function (a,b) { return [a].concat(b); });
append.defmethod('Array,*', function (a,b) { return a.concat([b]); });

append([1,2],[3,4]); // => [1,2,3,4]
append(1,[2,3,4]);   // => [1,2,3,4]
append([1,2,3],4);   // => [1,2,3,4]
append(1,2,3,4);     // => throws "No method found for append with args: number,number,number,number

Here’s a link directly to the exercise, but if you register for the site with this link, I get bonus points.

l