Created
September 8, 2015 09:59
-
-
Save darul75/065d946fb887c7d9d037 to your computer and use it in GitHub Desktop.
ramda functional js exercice
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
// Exercise 1 | |
//============== | |
// Refactor to remove all arguments by partially applying the function | |
var words = function(str) { | |
return _.split(' ', str); | |
}; | |
var match = R.curry(function(what, x) { | |
return x.match(what); | |
}); | |
var split = R.curry(function(what, x) { | |
return x.split(what); | |
}); | |
words = split(' '); | |
// Exercise 1a | |
//============== | |
// Use map to make a new words fn that works on an array of strings. | |
var sentences = R.map(words); | |
// Exercise 2 | |
//============== | |
// Refactor to remove all arguments by partially applying the functions | |
var filterQs = function(xs) { | |
return _.filter(function(x){ return match(/q/i, x); }, xs); | |
}; | |
var filter = R.curry(function(f, xs) { | |
return xs.filter(f); | |
}); | |
filterQs = filter(match(/q/i)); | |
// Exercise 3 | |
//============== | |
// Use the helper function _keepHighest to refactor max to not reference any | |
// arguments | |
// LEAVE BE: | |
var _keepHighest = function(x,y){ return x >= y ? x : y; }; | |
// REFACTOR THIS ONE: | |
var max = function(xs) { | |
return _.reduce(function(acc, x){ | |
return _keepHighest(acc, x); | |
}, -Infinity, xs); | |
}; | |
var reduce = R.curry(function(f, a, xs) { | |
return xs.reduce(f, a); | |
}); | |
var max = reduce(_keepHighest, 0); | |
// Bonus 1: | |
// ============ | |
// wrap array's slice to be functional and curried. | |
// //[1,2,3].slice(0, 2) | |
var slice = R.curry(function(s,e, xs) { | |
return xs.slice(s,e); | |
}); | |
var xs = [1,2,3,4,5]; | |
var s = slice(1, 3); | |
s(xs); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment