2015-08-05 07:27:56 +00:00
|
|
|
function isFreezable(object) {
|
2017-04-19 00:55:46 +00:00
|
|
|
if (object === null) return false
|
|
|
|
if (object instanceof RegExp) return false
|
2018-02-20 02:01:31 +00:00
|
|
|
if (object instanceof ArrayBuffer) return false
|
2015-08-03 17:37:26 +00:00
|
|
|
|
2017-04-19 00:55:46 +00:00
|
|
|
return Array.isArray(object) || typeof object === 'object'
|
2015-08-02 14:06:35 +00:00
|
|
|
}
|
2015-08-02 07:15:52 +00:00
|
|
|
|
2015-08-05 07:27:56 +00:00
|
|
|
function needsFreezing(object) {
|
2017-04-19 00:55:46 +00:00
|
|
|
return isFreezable(object) && !Object.isFrozen(object)
|
2015-08-02 07:15:52 +00:00
|
|
|
}
|
|
|
|
|
2015-08-05 07:27:56 +00:00
|
|
|
function recur(object) {
|
2017-04-19 00:55:46 +00:00
|
|
|
Object.freeze(object)
|
2015-08-02 07:15:52 +00:00
|
|
|
|
2020-04-02 14:16:13 +00:00
|
|
|
Object.keys(object).forEach((key) => {
|
2017-04-19 00:55:46 +00:00
|
|
|
const value = object[key]
|
2015-08-02 14:06:35 +00:00
|
|
|
if (needsFreezing(value)) {
|
2017-04-19 00:55:46 +00:00
|
|
|
recur(value)
|
2015-08-02 07:15:52 +00:00
|
|
|
}
|
2017-04-19 00:55:46 +00:00
|
|
|
})
|
2015-08-02 07:15:52 +00:00
|
|
|
|
2017-04-19 00:55:46 +00:00
|
|
|
return object
|
2015-08-02 07:15:52 +00:00
|
|
|
}
|
|
|
|
|
2015-08-19 14:29:06 +00:00
|
|
|
/**
|
|
|
|
* Deeply freeze a plain javascript object.
|
|
|
|
*
|
|
|
|
* If `process.env.NODE_ENV === 'production'`, this returns the original object
|
2016-05-30 21:37:41 +00:00
|
|
|
* without freezing.
|
|
|
|
*
|
|
|
|
* Or if `process.env.UPDEEP_MODE === 'dangerously_never_freeze'`, this returns the original object
|
|
|
|
* without freezing.
|
2015-08-19 14:29:06 +00:00
|
|
|
*
|
|
|
|
* @function
|
|
|
|
* @sig a -> a
|
|
|
|
* @param {object} object Object to freeze.
|
|
|
|
* @return {object} Frozen object, unless in production, then the same object.
|
|
|
|
*/
|
|
|
|
function freeze(object) {
|
2015-08-02 07:15:52 +00:00
|
|
|
if (process.env.NODE_ENV === 'production') {
|
2017-04-19 00:55:46 +00:00
|
|
|
return object
|
2015-08-02 07:15:52 +00:00
|
|
|
}
|
|
|
|
|
2016-05-30 21:37:41 +00:00
|
|
|
if (process.env.UPDEEP_MODE === 'dangerously_never_freeze') {
|
2017-04-19 00:55:46 +00:00
|
|
|
return object
|
2016-05-30 21:37:41 +00:00
|
|
|
}
|
|
|
|
|
2015-08-05 07:27:56 +00:00
|
|
|
if (needsFreezing(object)) {
|
2017-04-19 00:55:46 +00:00
|
|
|
recur(object)
|
2015-08-02 07:15:52 +00:00
|
|
|
}
|
|
|
|
|
2017-04-19 00:55:46 +00:00
|
|
|
return object
|
2015-08-02 07:15:52 +00:00
|
|
|
}
|
2015-08-19 14:29:06 +00:00
|
|
|
|
2017-04-19 00:55:46 +00:00
|
|
|
export default freeze
|