Skip to content

Instantly share code, notes, and snippets.

@jorinvo
Created July 2, 2013 23:33
Show Gist options
  • Save jorinvo/5914181 to your computer and use it in GitHub Desktop.
Save jorinvo/5914181 to your computer and use it in GitHub Desktop.
some experimentation with functional programming. partial application and composition is awesome! after writing it in js I felt like rewriting in coffescript. its really nice to get rid of all the `function` and `return` keywords. And [splats](http://coffeescript.org/#splats) are damn useful when you work with the arguments object.
_ =
pop: (ctx) ->
Array::pop.call ctx
slice: (args..., ctx) ->
Array::slice.apply ctx, args
reduce: (args..., ctx) ->
Array::reduce.apply ctx, args
reduceRight: (args..., ctx) ->
Array::reduceRight.apply ctx, args
concat: (args..., ctx) ->
Array::concat.apply _.slice(ctx), args
compose: (fns...) ->
(args...) ->
_.reduceRight((args, fn) ->
[ fn args... ]
, args, fns)[0]
partial: (part..., fn) ->
(args...) ->
fn _.concat( args, part )...
add = (args...) ->
_.reduce ((a, b) ->
a + b
), args
bang = (a) ->
a + "!"
adder = _.partial(1, 2, add)
addbang = _.compose(bang, adder)
magic = _.partial(1, 7, addbang)
res = magic(20)
console.log(res)
var _ = (function (arr) {
var _ = {
pop: function (ctx) {
return arr.pop.call(ctx);
},
slice: function () {
return arr.slice.apply( _.pop(arguments), arguments );
},
reduce: function () {
return arr.reduce.apply( _.pop(arguments), arguments );
},
reduceRight: function () {
return arr.reduceRight.apply( _.pop(arguments), arguments );
},
concat: function () {
return arr.concat.apply( _.slice( _.pop(arguments) ), arguments );
},
compose: function () {
var fns = arguments;
return function () {
return _.reduceRight(function (args, fn) {
return [ fn.apply(null, args) ];
}, arguments, fns)[0];
};
},
partial: function () {
var fn = _.pop(arguments);
var args = arguments;
return function () {
return fn.apply( null, _.concat( _.slice(arguments), args ) );
};
}
};
return _;
})(Array.prototype);
function add () {
return _.reduce(function (a, b) {
return a + b;
}, arguments);
}
function bang (a) {
return a + '!';
}
var adder = _.partial(1, 2, add);
var addbang = _.compose( bang, adder );
var magic = _.partial( 1, 7, addbang );
var res = magic(20, 7);
console.log(res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment