I\'m just starting to research different programming styles (OOP, functional, procedural).
I\'m learning JavaScript and starting into underscore.js and came along this s
There's no correct definition for what is and isn't "functional", but generally functional languages have an emphasis on simplicity where data and functions are concerned.
Most functional programming languages don't have concepts of classes and methods belonging to objects. Functions operate on well-defined data structures, rather than belonging to the data structures.
The first style _.map
is a function in the _
namespace. It's a standalone function and you could return it or pass it to another function as an argument.
function compose(f, g) {
return function(data) {
return f(g(data));
}
}
const flatMap = compose(_.flatten, _.map);
It's not possible to do the same for the second style, because the method instance is intrinsically tied to the data used to construct the object. So I'd say that the first form is more functional.
In either case, the general functional programming style is that data should be the final argument to the function, making it easier to curry or partially apply the earlier arguments. Lodash/fp and ramda address this by having the following signature for map.
_.map(func, data);
If the function is curried, you can create specific versions of the function by only passing the first argument.
const double = x => x * 2;
const mapDouble = _.map(double);
mapDouble([1, 2, 3]);
// => [2, 4, 6]