public
Last active

Examples from the functional javascript meetup

  • Download Gist
functional.meetup.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
// To play around with this code, copy and paste the contents of this gist
// into the javascript pane of http://jsbin.com/umoK/1/edit or go to
// http://jsbin.com/uZAfIqA/2/edit
 
// =============================================================================
// Generic API
// =============================================================================
 
//+ words :: string -> array
var words = split(' ');
 
//+ not :: _ -> boolean
var not = function (x) { return !x; };
 
//+ uniqBy :: array -> array
var uniqBy = function (param, arr) {
return reduce(function (memo, item) {
var items = pluck(param, memo);
return (_.indexOf(item[param], items) > -1) ? memo : push(item, memo);
}, [], arr);
}.autoCurry();
 
//+ arrayToTuples :: array -> array
var arrayToTuples = reduce(function(memo, item, index, list) {
return push([item, list[index+1]], memo);
}, []);
 
 
 
// =============================================================================
// Application API
// =============================================================================
 
//+ isVoteString :: string -> boolean
var isVoteString = test(/^[\+|\-]\d+$/);
 
//+ isValidVote :: object -> boolean
var isValidVote = function (vote) {
return vote.user && vote.points;
};
 
//+ tupleToVote :: array -> object
var tupleToVote = function (tuple) {
return {
points: find(isVoteString, tuple),
user: find(compose(not, isVoteString), tuple)
};
};
 
//+ getAllVotes :: string -> array
var getAllVotes = compose(map(tupleToVote), arrayToTuples, words);
 
//+ getUniqVotes :: string -> array
var getUniqVotes = compose(uniqBy('user'), filter(isValidVote), getAllVotes);
 
 
 
// =============================================================================
// Execution Logic
// =============================================================================
 
var input = '-1 kevin +1 kevin +1 test +1 +1 joe +1';
 
compose(console.log, getUniqVotes)(input);

This bit of code is an excerpt from an IRC bots vote validation. Every time a user posts a message to a channel, the bot will parse it for strings such as "+1 kevin for being awesome" and send a vote request to an api. We use this as an impromptu http://www.bash.org/ where we can record highlights from irc and vote and sort on them at a later point.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.