Consider this contrived example of string manipulation. We want to convert a string to uppercase
and append "!"
.
Procedural style code:
function test(str) {
return str.toUpperCase() + "!";
}
console.log(test("hello"));
// HELLO!
Let's decouple the two operations using a functional style
let Box = function(x) {
let err = false;
if (!x) err = true;
return {
map: f => err? Box(x): Box(f(x)),
flatMap: f => err? Box(x): f(x),
subscribe: (f, g) => err? g("Input Missing"): f(x)
};
};
Box("hello")
.map(s => s.toUpperCase())
.map(s => s + "!")
.subscribe(success => console.log(success),
error => console.log(error));
// HELLO!
Box("hello")
.flatMap(s => Box(s.toUpperCase()))
.flatMap(s => Box(s + "!"))
.subscribe(success => console.log(success),
error => console.log(error));
// HELLO!
Box()
.map(s => s.toUpperCase())
.flatMap(s => Box(s + "!"))
.subscribe(success => console.log(success),
error => console.log(error));
// Input missing