Created
March 19, 2024 18:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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