Searching lists of maps

Now that you know Immutable.js is capable of performing the heavy lifting involved with deep equality checking, let's see how it applies to searching collections. With some methods, you can simply pass the collection for which you want to search. This collection is then compared against every value in the other collection. Here's how this works with the includes() method:

const myList = List.of(
Map.of('one', 1),
Map.of('two', 2),
Map.of('three', 3)
);
const includesOne = myList.includes(Map.of('one', 1));

console.log('includesOne', includesOne);
// -> includesOne true

The includes() method uses the is() function for comparisons. Since you're passing in a collection, you're ultimately calling the equals() method on every value in the collection until one of them returns true. What if you want to perform this type of deep equality check with the filter() function? You can't simply pass it a collection—it expects a predicate function. No problem—just do the following:

const is = a => b => a.equals(b);

With this handy little utility, you can compose predicate functions that do deep comparison of everything in the collection with whatever you pass to is():

const myFilteredList = myList.filterNot(is(Map.of('one', 1)));

console.log('myFilteredList', myFilteredList.toJS());
// -> myFilteredList [ { two: 2 }, { three: 3 } ]

Remember, your version of is() returns a function to be used as a predicate with filter() or any other collection method that takes a predicate argument.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.97.64