Skip to content

Instantly share code, notes, and snippets.

@mrkev
Created May 30, 2016 17:01
Show Gist options
  • Save mrkev/15764e3ccdd1ee5c3a672140932a5835 to your computer and use it in GitHub Desktop.
Save mrkev/15764e3ccdd1ee5c3a672140932a5835 to your computer and use it in GitHub Desktop.
Currying a function in js
"use strict";
/* global require, console, module */
var arr = function (x) {
return Array.prototype.slice.call(x);
};
var args = function (str) {
return str.substring(str.indexOf("(")+1, str.indexOf(")")).split(",");
};
var curry = function (fun, total, args) {
if (!args) args = [];
var base = function () {
var curr_args = arr(arguments);
return fun.apply(this, args.concat(curr_args));
};
var indve = function () {
var prev_args = args.concat(arr(arguments));
return curry(fun, total-1, prev_args);
};
indve.toString = base.toString = function () {
return fun.toString() + " (" + args.join(",") + ", ...)";
};
return (total === 1) ? base : indve;
};
Function.prototype.curry = function () {
var first_line = this.toString().split("\n")[0];
return curry(this, args(first_line).length, []);
};
if (require.main === module) {
var echo = function () {
console.log('lomo', arr(arguments));
};
var add = function (a, b, c) {
return a + b + c;
};
var cadd = curry(add,3);
console.log(cadd(1)(2)(1));
var cecho = curry(echo, 3);
console.log(cecho(1)(2)(1));
var woah_add = add.curry();
console.log(woah_add(1)(2));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment