Freeze-Mutate: An Immutable Object Management Library for JS and TS

Ethan Ram
Ethan Ram
Sep 15, 2018 · 3 min read

I was looking for a nice little module that would help me get my DTOs immutable. The libraries I found were either an overkill (immutable.js), lacking support for deep merging of objects during mutations, or they were making my code ugly with lots of function calls for each change. So that’s how freeze-mutate came to life: A Javascript/Typescript-based npm module that helps me keep things simple and neat.

  • Freeze any object and it becomes deeply-immutable: all its properties and child-objects are frozen in the process. This is done by calling recursively to Javascript’s native Object.freeze.
  • Mutate a frozen object with a change-set and you get a new frozen object that is a merge, or an overlay, of a change-set on top of the original object. Again, this is a deep-merge that also works with Arrays, Sets, Maps, and your own custom classes. For the brave: you can provide custom freeze and merge functions.
  • Using Typescript you get all the goodies of generics, enforcing the validity of the change-set, Readonly returned types and interfaces for the custom functions.

Enough talking. Let’s dive in…

Deep-freezing and merging of objects and Arrays during mutation:

freeze and mutate a pojo with a couple of child objects and a child array

Support for Set and Map and class objects (aka you might want to skip immutable.js)

freeze and mutate an object with an extended Set

Support for cyclic objects

freeze and mutate a cyclic pojo

Even more interesting cyclic objects…

a complex cyclic inside a Map

For Typescript we have here some more goodies!

More features:

  1. Zero dependencies and just 2 KB pkg.
  2. Can be loaded in a browser.
  3. Be careful with mutating large objects, arrays and Maps — this is heavy!
  4. Code is fully covered with jest tests.

For more details head for the readme on git

You are welcome to star/clap/like/share to show me how awesome you are and help others find this lib. ;-)

Cheers!

eram at weblegions dot com

Originally published at github.com.

DailyJS

JavaScript news and opinion.

Ethan Ram

Written by

Ethan Ram

R&D lead; out-of-the-box thinker; able to break monumental projects into chewable bites; the null-terminator!

DailyJS

DailyJS

JavaScript news and opinion.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade