-
Notifications
You must be signed in to change notification settings - Fork 0
/
deepFreeze.js
55 lines (45 loc) · 1.14 KB
/
deepFreeze.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'use strict'
module.exports = {
deepFreeze: deepFreeze,
deepClone: deepClone,
makeClonable: makeClonable,
makeClonableAndDeepFreeze: makeClonableAndDeepFreeze
}
function deepFreeze (o) {
Object.freeze(o)
Object.getOwnPropertyNames(o)
.map(n => o[n])
.filter(_shouldFreeze)
.forEach(deepFreeze)
}
function deepClone (o) {
const newO = Object.assign({}, o)
Object.getOwnPropertyNames(newO)
.filter(p => _shouldClone(newO[p]))
.forEach(p => { newO[p] = deepClone(newO[p]) })
return newO
}
function makeClonable (obj) {
obj.cloneAndRefreeze = (changesCallback) => {
const clone = deepClone(obj)
if (typeof changesCallback === 'function') changesCallback(clone)
makeClonable(clone)
deepFreeze(clone)
return clone
}
}
function makeClonableAndDeepFreeze (obj) {
makeClonable(obj)
deepFreeze(obj)
}
function _shouldFreeze (x) {
if (x === null) return false
if (typeof x !== 'object' && typeof x !== 'function') return false
if (Object.isFrozen(x)) return false
return true
}
function _shouldClone (x) {
if (x === null) return false
if (typeof x !== 'object') return false
return true
}