another-deep-freeze
v1.0.0
Published
Util to make your objects and arrays purely immutable
Downloads
1,468
Maintainers
Readme
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.
import deepFreeze from 'another-deep-freeze'
const txn = {
_id: 1,
amount: 1000.0,
branch: {
_id: 1,
tellers: [1, { _id: 2, code: 'XYZ001' }]
}
}
// freeze txn in a cloned object
const frozenTxn = deepFreeze(txn)
txn === frozenTxn // false
The following operations will throw TypeError
// 1. mutating existing key
frozenTxn._id = 2
// 2. adding new key
frozenTxn.newKey = 1
// 3. deleting a key
delete forzenTxn.branch
// same behaviour at all depths
frozenTxn.branch._id = 2
// even for an array
frozenTxn.branch.tellers.push(0)
// or an array of objects
frozenTxn.branch.tellers[1].code = 'NEWCODE'
// the prototypes are immutable and any attempt of mutation will throw TypeError
Object.setPrototypeOf(frozenTxn, { foo: 'baz' })
txn.branch.__proto__.foo = 'baz'
txn.branch.tellers.__proto__.length = 0
You may also perform in-place deep freeze.
import deepFreeze from 'another-deep-freeze'
const txn = {
_id: 1,
amount: 1000.0,
branch: {
_id: 1,
tellers: [1, { _id: 2, code: 'XYZ001' }]
}
}
const sameTxn = deepFreeze(txn, /* in-place deep freeze*/ true)
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.