Skip to content

Instantly share code, notes, and snippets.

@mattdiamond
Last active December 4, 2017 18:13
Show Gist options
  • Save mattdiamond/0d3a8ea2430bc6cfa6237a2030bb0414 to your computer and use it in GitHub Desktop.
Save mattdiamond/0d3a8ea2430bc6cfa6237a2030bb0414 to your computer and use it in GitHub Desktop.
Flexible curry function

Based on version in Underscore-Contrib, but without enforcing unary.

var curry = (function(){
	function collectArgs(func, context, argCount, args, newArgs){
		args = args.concat(Array.from(newArgs));
		if (args.length >= argCount){
			return func.apply(context || this, args);
		}
		return function(){
			return collectArgs.call(this, func, context, argCount, args, arguments);
		};
	}
	return function curry(func, context){
		return function(){
			return collectArgs.call(this, func, context, func.length, [], arguments);
		};
	};
})();

Shorter version:

function curry(func, context){
	let args = [];
	return function collectArgs(){
		args = args.concat(Array.from(arguments));
		if (args.length >= func.length){
			return func.apply(context || this, args);
		}
		return function(){
			return collectArgs.apply(this, arguments);
		}
	};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment