Last active
October 22, 2016 01:15
-
-
Save spmurrayzzz/503558bbe011cec06bf8215a839d91d2 to your computer and use it in GitHub Desktop.
Immutable object factory, using proxies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const immutable = require('./immutable'); | |
let obj; | |
obj = immutable({ foo: 'bar' }); | |
obj.foo = 'baz'; // assignment fails silently | |
delete obj.foo; // delete fails silently | |
obj = immutable({ foo: [ 1, 2, 3 ] }); | |
obj.foo.push( 4 ); // mutation fails silently | |
obj = immutable({ foo: { bar: true } }); | |
obj.foo.bar = false; // deep assignment fails silently |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
function isObject( arg ) { | |
const t = typeof arg; | |
return ( t === 'object' || t === 'function' ) && arg !== null; | |
} | |
const immutableHandler = { | |
get( target, prop ) { | |
const val = Reflect.get( target, prop ); | |
if ( isObject( val ) ) { | |
return new Proxy( val, immutableHandler ); | |
} | |
return val; | |
}, | |
set() { | |
return true; | |
}, | |
deleteProperty() { | |
return true; | |
} | |
}; | |
module.exports = val => new Proxy( val, immutableHandler ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment