Shishir Arora
Shishir Arora

Reputation: 5943

lodash: v3.10.1 not compatible with v2.4.1. How to make backward compatible?

Came across a following difference:
Example 1

var s = [];
var anArray = [1,2,3];
var iterateeFunction = function(n){
       s.push(n);
}

_( anArray ).forEach( iterateeFunction )

Output:

Example 2

_.first([1, 2, 3], 2);

Output:

Not sure if this is really an incompatibility! @John-David Dalton: Please Advise: What was the need to change this? Compatibility issues just for this! I dont think its a sufficient cause.

This may be incorrect way of using lodash but on older versions it anyways worked. I think there may be more such instances. So My question is

  1. Are there anymore such instances? How big a risk it is, to change my project's current version to the latest version?
  2. how to tackle such issues such that older functionalities remain intact + I also get to use the newer utility functions in v3.10.1?

I really like v3.10.1 and I would love to upgrade!

Upvotes: 2

Views: 474

Answers (1)

user2864740
user2864740

Reputation: 61975

This difference has to do with the new lazy sequences added in version 3.

The result is that each/forEach processing, which are used for side-effects, has lead to much confusion and "bug" reports - see "Lazy each should cause immediate evaluation", "Each doesn't execute callbacks when wrapped", etc.

The change to lazy sequence processing may break any sequence-operation callback that expected immediate execution (ie. performed a side-effect) that is not otherwise immediately forced or materialized. The problem will most often be encountered in each/forEach usage - where the pass-through sequence is generally ignored - but it can also manifest in other 'unexpectedly delayed' executions.

To make the v3 code act as before, force or "unwrap" the sequence with value.

   _( anArray ).forEach( iterateeFunction ).value()
//   ^-- creates lazy sequence
//              ^-- so this doesn't "run" the callback
//                                          ^-- until unwrapped

or, better, use the non-wrapped form:

_( anArray, iterateeFunction )

or, better, with ES5-compatible functions (where it is an array as the object):

anArray.forEach(iterateFunction)

Upvotes: 1

Related Questions