Skip to content

Instantly share code, notes, and snippets.

@saiashirwad
Created February 14, 2025 20:56
Show Gist options
  • Save saiashirwad/de2c878d5700402ca79e1a5e5591217a to your computer and use it in GitHub Desktop.
Save saiashirwad/de2c878d5700402ca79e1a5e5591217a to your computer and use it in GitHub Desktop.
ez signals in ts
let activeEffect: (() => void) | null = null;
export function signal<T>(initialValue: T) {
let value = initialValue;
const subscribers = new Set<() => void>();
return {
get(): T {
if (activeEffect) {
subscribers.add(activeEffect);
}
return value;
},
set(newValue: T): void {
if (value === newValue) return;
value = newValue;
subscribers.forEach((subscriber) => subscriber());
},
};
}
export function effect(fn: () => void) {
const execute = () => {
const prevEffect = activeEffect;
activeEffect = execute;
try {
fn();
} finally {
activeEffect = prevEffect;
}
};
execute();
}
export function computed<T>(fn: () => T) {
const result = signal<T>(fn());
effect(() => result.set(fn()));
return result;
}
const count = signal(0);
const doubled = computed(() => count.get() * 2);
effect(() => {
console.log("Count:", count.get());
console.log("Doubled:", doubled.get());
});
count.set(5);
export type Signal<T> = ReturnType<typeof signal<T>>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment