Skip to content

Instantly share code, notes, and snippets.

@crutchcorn
Created March 19, 2024 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crutchcorn/dc66e887eb5573a3c7ce43c9c162bed5 to your computer and use it in GitHub Desktop.
Save crutchcorn/dc66e887eb5573a3c7ce43c9c162bed5 to your computer and use it in GitHub Desktop.
A basic implementation of Signals from scratch written in 5 minutes for ngConf 2024
function signal<T>(initialValue: T) {
let value: T = initialValue;
function getValue() {
return value;
}
getValue.set = (newValue: T) => {
value = newValue;
}
return getValue;
}
const count = signal(0);
console.log(count()); // 0
count.set(1);
console.log(count()); // 1
let Listener: (() => void) | null = null;
function signal<T>(initialValue: T) {
let value: T = initialValue;
let subscribers = new Set<() => void>()
function getValue() {
if (Listener) {
subscribers.add(Listener)
}
return value;
}
getValue.set = (newValue: T) => {
value = newValue;
subscribers.forEach(fn => fn())
}
return getValue;
}
function computed<T>(fn: () => T) {
let value!: T;
Listener = () => {
value = fn()
}
value = fn();
Listener = null
function getValue() {
return value;
}
return getValue;
}
const count = signal(0);
const doubleCount = computed(() => count() * 2)
console.log(count()); // 0
count.set(1);
console.log(count()); // 1
console.log(doubleCount()); // 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment