How to use immutable

Comprehensive immutable code examples:

How to use immutable.Collection:

4
5
6
7
8
9
10
11
12
13
14
15
const throwError = msg => {
  throw new Error(msg)
}


const toJS = x =>
  x instanceof im.Collection
    ? x.toJS()
    : x


// Language primitives

How to use immutable.default:

437
438
439
440
441
442
443
444
445
446
        });
        uploadedFiles.set(uploadCacheKey, hash);
    }
    const hash = uploadedFiles.get(uploadCacheKey);
    (0, spinner_1.step)(spinner, '              ..', `${hash}${alreadyUploaded ? ' (already uploaded)' : ''}`);
    return immutable_1.default.fromJS({ '/': `/ipfs/${hash}` });
}
async _uploadSubgraphDefinitionToIPFS(subgraph) {
    const str = js_yaml_1.default.safeDump(subgraph.toJS(), { noRefs: true, sortKeys: true });
    const file = { path: 'subgraph.yaml', content: Buffer.from(str, 'utf-8') };

How to use immutable.isAssociative:

14
15
16
17
18
19
20
21
22
23
def apply[T](collection: Iterable[T]): Indexed[T] = js.native
def apply[V](obj: StringDictionary[V]): Keyed[String, V] = js.native
/**
  * @deprecated use `const { isAssociative } = require('immutable')`
  */
def isAssociative(maybeAssociative: js.Any): Boolean = js.native
/**
  * @deprecated use `const { isIndexed } = require('immutable')`
  */
def isIndexed(maybeIndexed: js.Any): /* is immutable.Immutable.Collection.Indexed<any> */ Boolean = js.native

How to use immutable.setIn:

52
53
54
55
56
57
58
59
60
61
62
63
        const resp = setIn(state, [typeData], fromJS(updatedFortalezas))
        setData(resp)
        return resp


    }
    const resp = setIn(state, [typeData, ixToUpdate, action.payload.field], action.payload.text)
    setData(resp)
    return resp


}

How to use immutable.get:

36
37
38
39
40
41
42
43
44
45
46
    setData(resp.toJS())
    return resp
}


const updateAnalyze = (typeData, state, action) => {
    const ixToUpdate = get(state, typeData).findIndex(
        (item) => (get(item, 'id') === action.payload.id)
    )
    if (ixToUpdate < 0) {
        return state;

How to use immutable.Range:

How to use immutable.js:

182
183
184
185
186
187
188
189
190
191
 *
 * @param {string|Array.<string>} [path] - defaults to empty string. Can be array for path. See Immutable.js Cursors
 *
 * @api public
 * @module structure.cursor
 * @returns {Cursor} Gives a Cursor from Immutable.js
 */
Structure.prototype.cursor = function (path) {
  var self = this;
  path = valToKeyPath(path) || [];

How to use immutable.Repeat:

31
32
33
34
35
36
37
38
39
40
41
42


var sanitizeDraftText = require("./sanitizeDraftText");


var List = Immutable.List,
    Record = Immutable.Record,
    Repeat = Immutable.Repeat;
var defaultRecord = {
  entityMap: null,
  blockMap: null,
  selectionBefore: null,

How to use immutable.Seq:

35
36
37
38
39
40
41
42
43
44
```

This might feel a little over the top at first but comes with a few advantages that are pivotal to >TreeUtils.
As a matter of fact, all the functions in this lib, that give you a node or a collection of nodes don't return the actual >ImmutableJS values but the key paths to the substate where the resulting node(s) are located. A lot of operations become very trivial with key paths. Let's look at the >parent function. Determining the parent of a given node represented by a key path is as simple as this:
```js
let nodePath = Immutable.Seq(['data', 'childNodes', 0, 'childNodes', 1]);
let parentPath = nodePath.skipLast(2);
```

The actual retrieval of the >ImmutableJS values is left to you, but you will notice that working with key paths can be quite fun. Imagine you want to get value at key `content` of the next sibling of a given node. You could do this like so:

How to use immutable.Iterable:

123
124
125
126
127
128
129
130
131
132
133
134
	 */
	const fs 		= require('fs');
	/**
	 * @inheritdoc
	 */
	const isKeyed 	= Imm.Iterable.isKeyed;


	


/////////////////////////////////////////////////////////////////////////////////////////////

How to use immutable.is:

722
723
724
725
726
727
728
729
730
731
*
*     var date1 = new Date(1234567890000); // Fri Feb 13 2009 ...
*     var date2 = new Date(1234567890000);
*     date1.valueOf(); // 1234567890000
*     assert( date1 !== date2 );
*     assert( Immutable.is( date1, date2 ) );
*
* Note: overriding `valueOf` may have other implications if you use this object
* where JavaScript expects a primitive, such as implicit string coercion.
*

How to use immutable.Record:

158
159
160
161
162
163
164
165
166

TreeNode.asMutable = asMutable;
function asMutable(tree) {
    const children = tree.getChildren().map(asMutable).asMutable();
    tree = tree.set('children', children);
    return Immutable.Record.prototype.asMutable.call(tree);
}

module.exports = TreeNode;

How to use immutable.OrderedSet:

554
555
556
557
558
559
560
561
562
563
564
565
  return structure;
};




function subscribe(listeners, path, fn) {
  return listeners.updateIn(path.concat(LISTENER_SENTINEL), Immutable.OrderedSet(), function(old) {
    return old.add(fn);
  });
}

How to use immutable.Set:

262
263
264
265
266
267
268
269
270
271

path = valToKeyPath(path) || [];

var self = this,
    cursor = this.cursor(path),
    unobservers = Immutable.Set();

function cursorRefresher() { cursor = self.cursor(path); }
function _subscribe (path, fn) {
  self._referencelisteners = subscribe(self._referencelisteners, path, fn);

How to use immutable.OrderedMap:

282
283
284
285
286
287
288
289
290
291
this.monitorBlockInfo = {};

/**
 * Ordered map of all monitors, which are MonitorReporter objects.
 */
this._monitorState = OrderedMap({});

/**
 * Monitor state from last tick
 */

How to use immutable.fromJS:

100
101
102
103
104
105
106
107
108
109
  getAt: (arr, idx) => arr[idx],
  setAt: (arr, idx, val) => timm.replaceAt(arr, idx, val),
};

_solImmutableJs = {
  init: () => Immutable.fromJS(INITIAL_OBJECT), // deep
  get: (obj, key) => obj.get(key),
  set: (obj, key, val) => obj.set(key, val),
  getDeep: (obj, key1, key2) => obj.getIn([key1, key2]),
  setDeep: (obj, key1, key2, val) => obj.setIn([key1, key2], val),

How to use immutable.List:

109
110
111
112
113
114
115
116
117
  setDeep: (obj, key1, key2, val) => obj.setIn([key1, key2], val),
  getIn: (obj, path) => obj.getIn(path),
  setIn: (obj, path, val) => obj.setIn(path, val),
  merge: (obj1, obj2) => obj1.merge(obj2),
  mergeDeep: (obj1, obj2) => obj1.mergeDeep(obj2),
  initArr: () => Immutable.List(INITIAL_ARRAY), // shallow
  getAt: (arr, idx) => arr.get(idx),
  setAt: (arr, idx, val) => arr.set(idx, val),
};

How to use immutable.Map:

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