CURRY
A curry function without anything too clever
(... because hunger is the finest spice)
Why
If you don't know currying, or aren't sold on it's awesomeness, perhaps a friendly blog post will help.
API
curry
var curry = require('curry');
var add = curry(function(a, b){ return a + b });
add(1, 2)
var add1 = add(1);
add1(2)
var zipWith = curry(function(fn, a, b){
return a.map(function(val, i){ return fn(val, b[i]) });
});
var zipAdd = zipWith(add);
var zipAddWith123 = zipAdd([1, 2, 3]);
zipAdd([1, 2, 3], [1, 2, 3]);
zipAddWith123([5, 6, 7]);
zipWith.length;
zipAdd.length;
zipAddWith123.length;
curry.to
Sometimes it's necessary (especially when wrapping variadic functions) to explicitly provide an arity for your curried function:
var sum = function(){
var nums = [].slice.call(arguments);
return nums.reduce(function(a, b){ return a + b });
}
var sum3 = curry.to(3, sum);
var sum4 = curry.to(4, sum);
sum3(1, 2)(3)
sum4(1)(2)(3, 4)
curry.adapt
It's a (sad?) fact that JavaScript functions are often written to take the 'context' object as the first argument.
With curried functions, of course, we want it to be the last object. curry.adapt
shifts the context to the last argument,
to give us a hand with this:
var delve = require('delve');
var delveC = curry.adapt(delve);
var getDataFromResponse = delveC('response.body.data');
getDataFromResponse({ response: { body: { data: { x: 2 }} } });
curry.adaptTo
Like curry.adapt
, but the arity explicitly provided:
var _ = require('lodash');
var map = curry.adaptTo(2, _.map);
var mapInc = map(function(a){ return a + 1 })
mapInc([1, 2, 3])
installation
node/npm
npm install curry
amd
define(['libs/curry.min'], function(curry){
});
browser
If you're not using tools like browserify or require.js, you can load curry globally:
<script src="libs/curry.min.js"></script>
<script>
</script>
∏∏