same-old

2.0.0 • Public • Published

Same Old

Simple immutability for JavaScript objects/arrays/functions using Proxies. This is based on the excellent article here.

Libraries like Immutable.js and others are awesome, but I wanted something simple and lightweight (minified and gzipped it's less than 1k) to just give me immutability.

Install

Just run npm install same-old.

If you want to work on it, you can clone the repo and run the tests with npm run test.

Usage

const sameOld = require('same-old');
 
/*
Objects
*/
const immutable = sameOld({ cannot: 'change' });
 
immutable.cannot = 'change it'; // Throws
Object.assign(immutable, { cannot: 'ever change' }); // Throws
 
const deep = sameOld({ it: 'works', on: { nested: 'objects' } });
 
deep.on.nested = 'change'; // Throws
 
/*
Arrays
*/
const immutableArray = sameOld([5, 4, 3]);
 
immutableArray.push(2); // Throws
immutableArray.sort(); // Throws
console.log(immutableArray); // [5, 4, 3]
 
const derived = immutableArray.concat([2]); // [5, 4, 3, 2]
 
derived.push(1); // Throws
derived.sort(); // Throws
console.log(derived); // [5, 4, 3, 2]
 
/*
Functions
*/
const immutableFunc = sameOld(() => [1, 2, 3]);
const returnedArray = immutableFunc();
returnedArray.push(4); // Throws

Support

This uses Proxy and WeakMap so basically don't even bother on IE or anything old.

Readme

Keywords

Package Sidebar

Install

npm i same-old

Weekly Downloads

0

Version

2.0.0

License

Apache-2.0

Last publish

Collaborators

  • dominicp