Baz
Baz

Reputation: 13145

immutable.js: Map versus Seq

What the difference between a Map and a Seq in Immutable.js? Can you please provide an example demonstrating the difference between the two.

Upvotes: 1

Views: 1530

Answers (1)

VanDanic
VanDanic

Reputation: 432

Immutable’s Map is an unordered Iterable.Keyed which consists of (key, value) pairs.

// create a Map()
const map = Map({a: 1, b: 'Hello'});
// get a value for a specific key
console.log(map.get('b'));
> "Hello"
// set a new value and assign it to a new Map()
const newMap = map.set('c', 'This is a new key/value pair');
console.log(newMap.get('c'));
> "This is a new key/value pair"

It provides access to a variety of methods such as setIn(), deleteIn(), merge(), map() and so on. It can also be converted to other Immutable datatypes. You can see the the docs about all of these methods.

Immutable’s Seq is an Iterable sequence of values that does not need to have an underlying data structure. This is the first major difference from Map and you can see this in their definitions:

class Map<K, V> extends Collection.Keyed<K, V>

While:

class Seq<K, V> extends Iterable<K, V>

Right from the get-go we can see that Seq does not have keyed values, a major difference from Map. Another major difference is that you cannot append, update or delete elements from a Seq structure.

In addition, to quote Lee Byron:

A Seq is a lazy operation representation. You can think of it as a very light-weight container of a previous Iterable and some operation to apply (map, filter, etc), that operation is applied only when necessary to get a value. Seq doesn't store any values itself.

Because Seq is lightweight it can be rather performant for certain logic chains. The docs also note that it is often used to provide a rich collection API to JavaScript Object.

Upvotes: 4

Related Questions