I'm trying to understand functional composition in Javascript and followed a talk which describes the compose function
I tried the following program which will accept a sentence, break it up into pieces (delimited by space) and use uppercase on each word and return an array of words.
function compose(f, g) {
"use strict";
return function() {
return f.call(this, g.apply(this,arguments));
}
}
var split = function (string, delim) {
"use strict";
return string.split(delim);
};
var uppercase = function (string) {
"use strict";
if (string instanceof Array) {
return string.map(function (x) {
return x.toString().toUpperCase();
});
} else {
return string.toString().toUpperCase();
}
//return string.toString().toUpperCase();
};
var myfunc = compose(uppercase,split);
var data = myfunc("Elementary! My dear Watson",/\s+/);
console.log(data);
Though I got what I wanted, but the code is ugly on following counts:
- I've to re-define split and toUpperCase as I constantly got "Reference error: toUpperCase not defined". Is it because they are methods and not pure functions per se?
- the uppercase method is ugly because it should receive just a single string so that it flips the case,but since I'm tokenizing it, this function receives an array and hence the ugly array check.
How can the code be improvised to have a "pipe of functions" viz. split -> map -> uppercase ?