-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Documentation
compose :: (a_n-1 -> a_n) -> (a_n-2 -> a_n-1) -> .... -> (a_0 -> a_1) -> (a_0 -> a_n)
compose
takes any number of functions and returns the composite function roughly calculated as:
fc = compose (f1,f2,...,fn)(x) = f1 (f2(...fn-1 (fn (x))...))
Suppose that you need to upper case some string in some parts of your code, and separate it by spaces in others, so you write these functions:
function toUpperCase (s) {
return String.prototype.toUpperCase.call (s);
}
function splitBySpaces (s) {
return s.split (/\s/g);
}
Now you wan't to do both, you could off course write a new function, or just use the previous two every time, but with compose you could effortlessly get a new function that does this. Given
var s = "composing will not save you coding";
just use ramda.compose
as
var upperCaseSplit = ramda.compose (splitBySpaces, toUpperCase),
result = upperCaseSplit (s); //[ 'COMPOSING', 'WILL', 'NOT', 'SAVE', 'YOU', 'CODING' ]
Now, the message given by the result is wrong and we wish to correct it. Using this new function
function removeNOT (sList) {
return sList.filter ( function (s) {
return s.match (/^(not|NOT)/) ? false : true;
});
}
we just have to compose with the previous function and thats it!
var upperCaseSplitRemoveNot = compose (removeNOT, upperCaseSplit),
newResult = upperCaseSplitRemoveNot (s); //[ 'COMPOSING', 'WILL', 'SAVE', 'YOU', 'CODING' ]
Since composition is associative, we could've also defined the function as
var upperCaseSplitRemoveNot = compose (removeNOT, splitBySpaces, toUpperCase);
Notice that each function is actually very simple, easier to understand and thus maintain and debug.