简体   繁体   中英

Underscore and LoDash _.each

I'm in the process of migrating a code base from Underscore 1.8.2 to lodash 4.5.1. There was one test that failed after the migration.

The code being tested was a recursive summation using _.each .

function foo(elements) {
  if (elements.isContainer()) {
    var sum = 0;
    _.each(elements, function(element) {
      sum += foo(element);
    });
    return sum;
  } else {
    return elements.someAttr ? 1 : 0;
  }
}

Testing with an array that should be empty, 0 is expected as the result. underscore.each succeeded, but lodash did not (a positive value was returned).

I replaced the _.each(... with return _.sumBy(... , and the tests passed, but I am concerned that there may be more dormant issues within the code base.

Any ideas as to which difference between the two libraries would cause this?

Turns out the issue was actually in the test code. Above, elements was an array at runtime, but is the result of dereferencing a Knockout observable array. The spy created for the test was providing an observable instead of an array.

The difference between underscore and lodash here is that lodash uses Array.isArray to determine the type of the object passed. Underscore on the other hand just checks for the existence of the length property, which exists on Functions.

Underscore was treating the function as an Object, lodash was treating it as an Array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM