2

I have been using Immutable.js for some time, and just now I found out that the comparison operator does not work how I thought.

My code is simple:

a = Immutable.Map({a:1, b:[1,2,3]})
b = Immutable.Map({a:1, b:[1,2,3]})
a == b // false
Immutable.is(a, b) // false

Is there any way to compare two of the same Immutable objects and get true?

Functional logic tells me they should be equal, but in JavaScript they are not.

gariepy
  • 3,576
  • 6
  • 21
  • 34
Schovi
  • 1,960
  • 5
  • 19
  • 33
  • 1
    My guess is that `[1,2,3] != [1,2,3]` in your `b` key. Try to put the same object in both, or make it two immutable lists (or whatever they call it) – Bergi Aug 03 '15 at 15:59
  • don't know how `immutable` works but to make an obj comparison you need to build deep comparison function – maioman Aug 03 '15 at 16:20
  • Ah you are right! If I use `Immutable.fromJS` instead of `Immutable.Map` comparsion works fine. It is impractical for deep structures which are often changes to keep all objects inside immutable and dont forget some plain map or array. – Schovi Aug 04 '15 at 09:10

2 Answers2

3

a == b essentially compares "addresses" of two objects. And in your code you create two distinct instances of objects and so they are always different, therefore a == b is false by JavaScript specification.

As of how to compare two objects in JS, check this: Object comparison in JavaScript

Community
  • 1
  • 1
c-smile
  • 26,734
  • 7
  • 59
  • 86
  • `assert(a != b)` is expected, what about `Immutable.is`? – Pavlo Aug 03 '15 at 16:01
  • @Pavlo if `Immutable.is(a, b)` is really false then this is probably a bug in their implementation. Immutable.is definition is kind of fuzzy in their docs. – c-smile Aug 03 '15 at 16:26
0
(function () {
  var c = [1,2,3],
      a = Immutable.Map({a:1, b: c}),
      b = Immutable.Map({a:1, b:[1,2,3]});
  c[0] = 9;

  console.log(JSON.stringify(a), JSON.stringify(b));
}());

The way you are creating a and b would allow you to have side effects if you retained a reference (such as c) to the inner array as demonstrated above.

I think the comparisons are correctly telling you that the objects are not the same.

Jeremy Larter
  • 548
  • 2
  • 10
  • 21