Add freeze

This commit is contained in:
Aaron Jensen 2015-08-02 00:15:52 -07:00
parent f199cd335a
commit 3ef66e17e4
3 changed files with 90 additions and 0 deletions

32
lib/freeze.js Normal file
View File

@ -0,0 +1,32 @@
function isFreezable(obj) {
if (Object.isFrozen(obj)) {
return false;
}
return Array.isArray(obj) || typeof obj === 'object';
}
function recur(obj) {
Object.freeze(obj);
Object.keys(obj).forEach((key) => {
const value = obj[key];
if (isFreezable(value)) {
recur(value);
}
});
return obj;
}
export default function freeze(obj) {
if (process.env.NODE_ENV === 'production') {
return obj;
}
if (isFreezable(obj)) {
recur(obj);
}
return obj;
}

5
test/.eslintrc Normal file
View File

@ -0,0 +1,5 @@
{
"rules": {
"no-unused-expressions": 0
}
}

53
test/freeze.js Normal file
View File

@ -0,0 +1,53 @@
import { expect } from 'chai';
import freeze from '../lib/freeze';
describe('freeze', () => {
afterEach(() => {
delete process.env.NODE_ENV;
});
it('freezes objects', () => {
const obj = {};
freeze(obj);
expect(Object.isFrozen(obj)).to.be.true;
});
it('freezes nested objects', () => {
const obj = { foo: { bar: 3 } };
freeze(obj);
expect(Object.isFrozen(obj.foo)).to.be.true;
});
it('freezes nested arrays', () => {
const obj = [[0]];
freeze(obj);
expect(Object.isFrozen(obj)).to.be.true;
expect(Object.isFrozen(obj[0])).to.be.true;
});
it('ignores functions', () => {
const obj = { foo: () => 1 };
freeze(obj);
expect(Object.isFrozen(obj.foo)).to.be.false;
});
it('does not freeze children if the parent is already frozen', () => {
const obj = { foo: {} };
Object.freeze(obj);
freeze(obj);
expect(Object.isFrozen(obj.foo)).to.be.false;
});
it('does not freeze in production', () => {
process.env.NODE_ENV = 'production';
const obj = {};
freeze(obj);
expect(Object.isFrozen(obj)).to.be.false;
});
});