Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is `each` different from `for-loop` when returning a value?

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?

like image 400
KyleC Avatar asked Sep 15 '26 12:09

KyleC


1 Answers

This is caused due to the lack of return statement. Each function iterates over find but doesn't return anything. return statement in predicate returns the output to the each function where it is not expected

Example of working function:

var find = function(list, predicate) {
     var res = undefined/null/whatever;
     each(list, function(elem) {
         if (predicate(elem)) {
             res = elem;
         }
     });
     return res;
};

However this function is not efficient as it won't stop when result is found

like image 180
nesteant Avatar answered Sep 18 '26 00:09

nesteant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!