I have my each
function which I created to emulate Underscore.js's _each()
for my Javascript study.
var each = function(list, iteratee) {
if (Array.isArray(list)) { // list is array
for (var i = 0; i < list.length; i++) {
iteratee(list[i], i, list);
}
} else if (list.constructor === Object) { // list is object
for (var key in list) {
iteratee(list[key], key, list);
}
}
};
Then I wanted to create a function find
which is also available from Underscore.js. This function looks through each value in the list
, returning the first one that passes a truth test (predicate
), or
undefined
if no value passes the test. The function returns as soon as it finds an acceptable element and doesn't traverse the entire list.
Here is my version of find
that I came up with.
var find = function(list, predicate) {
each(list, function(elem){
if (predicate(elem)) {
return elem;
}
});
};
I thought it would return a value immediately after it has found a true value for an element that passes a test from an external predicate function. But instead, it's giving me an undefined
.
Below code works as I expected. But why would they provide different output?
var find = function(list, predicate) {
if (Array.isArray(list)) { // list is array
for (var i = 0; i < list.length; i++) {
if (predicate(list[i])) {
return list[i];
}
}
} else if (list.constructor === Object) { // list is object
for (var key in list) {
if (predicate(list[key])) {
return list[key];
}
}
}
};
What I don't understand is that why doesn't each
works as I expected when I included it in my find
function. Wouldn't they simply different in terms of their style of expression? In other word, one is functional style, and another is not?