Ok, I've been having this debate recently regarding performance,
basically I prefer to use good ol' vanilla JS loops ie. for/for in
then the JS frameworks for each eqiv. because further investigation
reveals a hit in performance every time the the each loop runs due to
the closure it creates. So I guess my question is which one is best to
use?
The main goal of using the functional style is in increasing of
abstraction and allowing to use polymorphic code blocks on each
element of a collection. E.g. once you've implemented a common
iteration over the collection applying passed function, you can
provide almost unlimited conditions of testing/sorting/searching and
so on actions on elements of the collection.
For example:
var array = [1, 2, 3];
array.map(function (item) {
return item % 2 != 0;
}); [1, 3]
Another function passed functional argument will cause another result.
Inside these methods there is casual loop iteration, but see how the
abstraction is increase. Try e.g. to implement unlimited search
condition for a collection/object. In first case you need to find by
name, in the other -- by name and surname, in the next one -- by name
and by special condition from the outside. For that you can implement
single iteration over the collection and encapsulate inside a method/
function. Then all is needed -- to pass a function which will be
applied to every element/property of that collection. And exactly
function -- because it's the most elegant way to organize unlimited
test/map/filter and so on conditions -- try in contrast to pass that
search conditions via simple object and iterate over the collection
and then on each iteration over that object -- that's just ugly. But
having a functional argument as a test condition -- it is simple and
elegant:
users.find(function (user) {
return user.name == "David"
});
users.find(function (user) {
return user.name == "David" && user.surname == "Surname";
});
users.find(function (user) {
return user.name == "David" && isActive(user);
});
And `.find` can look like:
users.find = function (funArg) {
for (var user in this.data) { // if (..has own ..)
if (funArg(this.data[user])) {
return this.data[user];
}
}
return null;
};
You can enhance this and provide additional argument e.g. `needAll` to
search all users satisfying the search condition.
Iterating every time via loop is a "copy-paste" code reuse.
Encapsulating this loop in a function a passing conditions via object
is a better code reuse, but limited and ugly search condition
implementation. So that's why the functional programming operates with
functions as arguments in this case.
Dmitry.