Another Deep Freeze
This utility will recursively make the Object/Array and all it's properties/items immutable.
Javascript provides a built-in utility (Object.freeze) for freezing objects but it only freezes immediate properties of the object. If a property's depth is greater than 1 it will still remain mutable.
Installation
NPM
npm i -S another-deep-freeze
Yarn
yarn add another-deep-freeze --save
Usage
Pass the object to deepFreeze
and generate an immutable clone.
const txn = _id: 1 amount: 10000 branch: _id: 1 tellers: 1 _id: 2 code: 'XYZ001' // freeze txn in a cloned objectconst frozenTxn = txn === frozenTxn // false
The following operations will throw TypeError
// 1. mutating existing keyfrozenTxn_id = 2// 2. adding new keyfrozenTxnnewKey = 1// 3. deleting a keydelete forzenTxnbranch// same behaviour at all depthsfrozenTxnbranch_id = 2// even for an arrayfrozenTxnbranchtellers// or an array of objectsfrozenTxnbranchtellers1code = 'NEWCODE' // the prototypes are immutable and any attempt of mutation will throw TypeErrorObjecttxnbranch__proto__foo = 'baz'txnbranchtellers__proto__length = 0
You may also perform in-place deep freeze.
const txn = _id: 1 amount: 10000 branch: _id: 1 tellers: 1 _id: 2 code: 'XYZ001' const sameTxn = sameTxn === txn // true
This will make txn
immutable at all depths.
Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update the tests as appropriate.