theater-mutable
v0.2.4
Published
A simple library but yet efficient for building mutable data structures
Readme
mutable
theater mutable is library used to manage mutable values and track there changes inside any typescript / javascript applications easily.
Installation
Using your favourite package manager:
$ npm install theater-mutableQuick Guide
Welcome to the wonderful world of mutable! 🎭 Let's dive in and learn how to make your data dance to your tune.
Creating Mutable Values
First, let's create some mutable values. Think of them as regular values with superpowers! 🦸♂️
import { mutable } from "theater-mutable";
// Create a mutable number
const count = mutable(42);
// Create a mutable string
const name = mutable("John");
// Create a mutable array
const todos = mutable(["Buy groceries", "Walk the dog"]);
// Create a mutable object
const user = mutable({
name: "John",
age: 30,
isAdmin: false,
});Reading Values
To peek at what's inside your mutable values, use the read function:
import { read } from "theater-mutable";
console.log(read(count)); // 42
console.log(read(todos)); // ['Buy groceries', 'Walk the dog']
console.log(read(user.name)); // 'John'Writing Values
Want to change things up? Use the write function to update your mutable values:
import { write } from "theater-mutable";
// Update a primitive value
write(count, 43);
// Update an array
write(todos, ["Buy groceries", "Walk the dog", "Take out trash"]);
// Update an object property
write(user.name, "Jane");Listening to Changes
The real magic happens when you want to react to changes! Subscribe to your mutable values to stay in the loop:
import { subscribe } from "theater-mutable";
// Subscribe to a primitive value
const unsubscribe = subscribe(count, (newValue) => {
console.log(`Count changed to: ${newValue}`);
});
// Later, when you're done listening
unsubscribe();Why Use Mutable Values?
Mutable values are like having a personal assistant who keeps track of all your data changes and notifies you when something interesting happens! 🎭
- Reactive Programming: Build applications that automatically update when data changes
- Type Safety: Full TypeScript support for type-safe data management
- Nested Updates: Changes in nested values automatically bubble up to parent values
- Clean Code: Separate your data management from your UI logic
A Real-World Example
Let's build a simple todo list to see it all in action:
import { mutable, read, write, subscribe } from "theater-mutable";
// Create our todo list state
const state = mutable({
todos: ["Buy groceries", "Walk the dog"],
newTodo: "",
});
// Listen for changes
subscribe(state, (newState) => {
console.log("State changed:", newState);
});
// Add a new todo
write(state.newTodo, "Take out trash");
write(state.todos, [...read(state.todos), read(state.newTodo)]);
write(state.newTodo, ""); // Clear the inputAnd just like that, you're ready to start building reactive applications with mutable values! 🎉
