added deepFreeze

This commit is contained in:
Luk 2024-01-24 14:06:19 +08:00
parent 35862f8a69
commit f84a4bb406

View File

@ -10,6 +10,37 @@ module.exports = {
sleep: (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms)),
deepFreeze (obj) {
if (typeof obj !== 'object' || obj === null) {
return obj
}
Object.freeze(obj)
const propNames = Object.getOwnPropertyNames(obj)
propNames.forEach(prop => {
const propValue = obj[prop]
// for nested object
if (
propValue && typeof propValue === 'object' &&
!Object.isFrozen(propValue)
) {
deepFreeze(propValue)
}
// for nested array
if (Array.isArray(propValue)) {
propValue.forEach(item => {
if (
item && typeof item === 'object' &&
!Object.isFrozen(item)
) {
deepFreeze(item)
}
});
Object.freeze(propValue) // Freeze the array itself
}
})
return obj
},
parse_json_anyway (value) {
try {
return JSON.parse(value)