How to use the Map function from immutable

Find comprehensive JavaScript immutable.Map code examples handpicked from public code repositorys.

immutable.Map is a JavaScript data structure that represents an immutable collection of key-value pairs, similar to a regular JavaScript object, but with additional features for efficient updates and memory management.

116
117
118
119
120
121
122
123
124
125
function render (state) {
  ReactDOM.render(<TodoApp state={state} />, mountNode);
}

// Default initial structure as immutable data.
var structure = immutable.Map({
  items: immutable.List(),
  text: ''
});
// Render out initial application
fork icon55
star icon0
watch icon0

+ 5 other calls in file

109
110
111
112
113
114
115
116
117
118
* the `predicate` function returns true.
*
* <!-- runkit:activate -->
* ```js
* const { Map } = require('immutable')
* Map({ a: 1, b: 2, c: 3, d: 4}).filter(x => x % 2 === 0)
* // Map { "b": 2, "d": 4 }
* ```
*
* Note: `filter()` always returns a new instance, even if it results in
fork icon20
star icon246
watch icon12

+ 3 other calls in file

How does immutable.Map work?

immutable.Map works by creating a new immutable data structure that represents a collection of key-value pairs. The Map object is created using a factory function that takes an iterable object (such as an array or another Map) or an object with key-value pairs as input. Once created, the Map object cannot be modified directly; instead, all operations on the Map return a new, modified Map object, while leaving the original object unchanged. This makes the Map object suitable for use in functional programming and other contexts where immutability is desirable. The Map object provides a variety of methods for accessing and manipulating its contents, including set(), get(), delete(), and update(). The Map object also supports efficient memory management and performance optimizations, such as structural sharing, that allow for efficient updates and comparisons of large data sets. By providing a simple and efficient way to represent and manipulate immutable collections of key-value pairs, immutable.Map can help to simplify and streamline complex JavaScript applications.

67
68
69
70
71
72
73
74
75
Then require it into any module.

<!-- runkit:activate -->
```js
const { Map } = require('immutable');
const map1 = Map({ a: 1, b: 2, c: 3 });
const map2 = map1.set('b', 50);
map1.get('b') + ' vs. ' + map2.get('b'); // 2 vs. 50
```
fork icon19
star icon88
watch icon7

+ 11 other calls in file

126
127
128
129
130
131
132
133
134
135

// Find the node to insert into
let subNode;
if (!exists) {
    // Create children for subdirectory
    const children = new Immutable.Map();
    // Create a directory node
    const value = options.createValue(
        // parent tree
        tree,
fork icon18
star icon75
watch icon7

+ 41 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const { Map } = require("immutable");

// Create a new Map object with some initial key-value pairs
const map1 = Map({
  name: "Alice",
  age: 30,
  city: "San Francisco",
});

// Use the 'set' method to add a new key-value pair to the map
const map2 = map1.set("occupation", "programmer");

// Use the 'get' method to retrieve the value of a key
console.log(`Name: ${map2.get("name")}`); // Output: Name: Alice

// Use the 'delete' method to remove a key-value pair from the map
const map3 = map2.delete("city");

// Use the 'update' method to modify a value in the map
const map4 = map3.update("age", (age) => age + 1);

// Output the final map object to the console
console.log(map4.toJS()); // Output: { name: 'Alice', age: 31, occupation: 'programmer' }

In this example, we use immutable.Map to represent and manipulate a collection of key-value pairs. We first create a new Map object map1 using the factory function and some initial key-value pairs. We then use the set() method to add a new key-value pair to the map, and the get() method to retrieve the value of a key. We use the delete() method to remove a key-value pair from the map, and the update() method to modify a value in the map. Finally, we output the final Map object to the console using the toJS() method, which converts the Map to a regular JavaScript object for easy output. By using immutable.Map, we can create and manipulate collections of key-value pairs in an immutable and efficient manner, without modifying the original object.

5
6
7
8
9
10
11
12
13
14
15
16
17


var denormalize = require('../src').denormalize;


var immutable = require('immutable');
var fromJS = immutable.fromJS;
var Map = immutable.Map;
var Record = immutable.Record;
var List = immutable.List;


var normalizr = require('normalizr');
fork icon3
star icon9
watch icon2

+ 8 other calls in file

23
24
25
26
27
28
29
30
31
32
33
34
    syms[name] = makeSym(name)
  }
  return syms[name]
}


const makeSet = (...xs) => im.Map(xs)
const makeList = (...xs) => im.List(xs)
const makeForm = (name, ...args) => makeList(sym(name), ...args)


const is = im.is
fork icon0
star icon3
watch icon1

192
193
194
195
196
197
198
199
200
201
202
203
 * @returns {Map} result
 */




function createResultBones() {
  return new _immutable.Map({
    country: null,
    hotels: (0, _immutable.Map)(),
    operators: null,
    meta: null,
fork icon0
star icon3
watch icon4

+ 5 other calls in file

36
37
38
39
40
41
42
43
44
45
        next();
    }
}, {override: true});


ui.setOptionIn(optPath, Immutable.Map({
    name: config.PLUGIN_SLUG,
    title: config.PLUGIN_NAME,
    active: true,
    tagline: config.TAG_LINE,
fork icon0
star icon2
watch icon3

595
596
597
598
599
600
601
602
603
604
[new Map([[['v'], 1]]), new Map([[['v'], 2]])],
[
  new Map([[[1], new Map([[[1], 'one']])]]),
  new Map([[[1], new Map([[[1], 'two']])]]),
],
[Immutable.Map({a: 0}), Immutable.Map({b: 0})],
[Immutable.Map({v: 1}), Immutable.Map({v: 2})],
[
  Immutable.OrderedMap().set(1, 'one').set(2, 'two'),
  Immutable.OrderedMap().set(2, 'two').set(1, 'one'),
fork icon0
star icon1
watch icon4

+ 219 other calls in file

308
309
310
311
312
313
314
315
316
317
STR = arg.toString();
BLN = (typeof(arg) == 'boolean');
DTE = (arg instanceof Date);
try { NAN = isNaN(eval(arg)); } catch (e) {}
// Fill-In Return
ANS = Imm.Map({
	bln: 	(BLN),
	dte: 	(DTE),
	txt: 	(NAN && typeof(arg) == 'string'),
	raw: 	(arg instanceof RegExp),
fork icon0
star icon1
watch icon2

+ 32 other calls in file

28
29
30
31
32
33
34
35
36
  schema: fromJS(schema),
});
const schemaPath = plugin ? ['models', 'plugins', plugin, model] : ['models', model];
const keys = plugin ? `plugins.${plugin}.${model}.editDisplay` : `${model}.editDisplay`;
const prevList = state.getIn(['schema', ...schemaPath, 'editDisplay', 'fields'], List());
const prevFields =  Object.keys(state.getIn(['schema', ...schemaPath, 'editDisplay', 'availableFields'], Map()).toJS());
const currentFields = Object.keys(attributes);
const fieldsToRemove = _.difference(prevFields, currentFields);
let newList = prevList;
fork icon0
star icon1
watch icon1

8
9
10
11
12
13
14
15
16
17
```

## Maps

```js
var map = Immutable.Map({ a: 1, b: 2, c: 3 })

map
  .set('b', 50)
  .get('b') // 50
fork icon0
star icon1
watch icon2

+ 3 other calls in file

1
2
3
4
5
6
7
8
9
10
var Cursor = require('immutable/contrib/cursor')
var fromJS = Immutable.fromJS
var immediateFunction = ((typeof window !== 'undefined') && window.requestAnimationFrame) || (function(cb) { setTimeout(cb, 0) })

function Store() {
  this._data = Immutable.Map()
  this._listeners = {}
  this._cursor = Cursor.from(this._data, [], this._onChange.bind(this))
  this._changeFired = true
  this._syncUpdate = false
fork icon0
star icon2
watch icon3

+ 9 other calls in file

21
22
23
24
25
26
27
28
29
30
### Understanding key paths

As you already know, with >ImmutableJS we retrieve nested values like this:

```js
let map = Immutable.Map({a: { b: 'c' }});
map.getIn(['a', 'b']);
// 'c'
```
We could say that the key path to the value `'c'` is `['a', 'b']`.
fork icon8
star icon77
watch icon3

71
72
73
74
75
76
77
78
79
80
    };
}

function single(uri) {
    const route = myro({ [uri]: 'uri' });
    let data = new Immutable.Map();
    let req = null;
    return {
        load(params) {
            if (req) cancelRequest(req);
fork icon4
star icon4
watch icon10

45
46
47
48
49
50
51
52
53
54

function Mapping(children, validator) {
  if (validator === void 0) {
    validator = alwaysValid;
  }
  children = Immutable.Map(children);
  var defaultValue = children.map(getChildDefault);

  return freeze({
    isValid: function(value) {
fork icon0
star icon8
watch icon3

0
1
2
3
4
5
6
7
8
9
10
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var xhr = require('xhr')
var Immutable = require('immutable')
var main = require('main-loop')


var state = Immutable.Map({
	current: Number(location.hash.slice(2) || '0') || 0,
	slides: ['# No Slides'],
	transition: false,
	direction: 'right'
fork icon2
star icon1
watch icon0

+ 4 other calls in file

72
73
74
75
76
77
78
79
80
81
82
83
84
};


exports.isValidTree = isValidTree;


var isImmutableTree = function isImmutableTree(tree) {
  return _immutable.Map.isMap(tree);
};


exports.isImmutableTree = isImmutableTree;

fork icon1
star icon8
watch icon0

32
33
34
35
36
37
38
39
40
41
const prevMonitorState = MonitorRecord({
    id,
    opcode: 'turtle whereabouts',
    value: '25'
});
const newMonitorDelta = Map({
    id,
    value: String(25)
});
r.requestAddMonitor(prevMonitorState);
fork icon3
star icon6
watch icon0

+ 2 other calls in file

6
7
8
9
10
11
12
13
14
15
16


router.get('/:id', function (req, res) {
  const watershed_id = req.params.id;
  const user_id = req.session.i7e.get('user_id');
  const summary = watersheds.summary(req.app.get('db'), watershed_id);
  let reports_by_level = Map();
  Range(0, summary.get('progression_level') + 1).reverse().forEach(
    function (level) {
      reports_by_level = reports_by_level.set(level, List());
    });
fork icon1
star icon1
watch icon2

+ 2 other calls in file