Skip to content

Instantly share code, notes, and snippets.

@spmurrayzzz
Last active October 22, 2016 01:15
Show Gist options
  • Save spmurrayzzz/503558bbe011cec06bf8215a839d91d2 to your computer and use it in GitHub Desktop.
Save spmurrayzzz/503558bbe011cec06bf8215a839d91d2 to your computer and use it in GitHub Desktop.
Immutable object factory, using proxies
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
'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