Last active
August 29, 2015 14:01
-
-
Save hikari-no-yume/2adb5a8f8c2acea124e3 to your computer and use it in GitHub Desktop.
Tiny function and operator curriers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function curry(func, arity) { | |
arity = (arity === undefined) ? func.length : arity; | |
if (arity > 1) { | |
return function (arg) { | |
var args = Array.prototype.slice.call(arguments, 0); | |
return function partial (arg) { | |
args = args.concat(Array.prototype.slice.call(arguments, 0)); | |
if (args.length < arity) { | |
return partial; | |
} else { | |
return func.apply(this, args); | |
} | |
}; | |
}; | |
} else { | |
return func; | |
} | |
} | |
function operatorFunction(isLeftArg, operator, isRightArg) { | |
var parts = []; | |
if (isLeftArg) { | |
parts.push('leftArg'); | |
} | |
if (isRightArg) { | |
parts.push('rightArg'); | |
} | |
parts.push('return (' + (isLeftArg ? 'leftArg ' : '') + operator + (isRightArg ? ' rightArg' : '') + ');'); | |
return Function.apply(Object.create(Function.prototype), parts); | |
} | |
function curryOperator(isLeftArg, operator, isRightArg) { | |
return curry(curryOperator(isLeftArg, operator, isRightArg), isLeftArg + isRightArg); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment