Created
April 28, 2024 08:49
-
-
Save helabenkhalfallah/472938a90cbd0f2eb538a95fa9b5ebef to your computer and use it in GitHub Desktop.
Simplified version of createSignal
This file contains hidden or 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
// Array to keep track of currently executing computations | |
const context = []; | |
// Function to add a computation (running) to the subscriptions of a signal | |
function subscribe(running, subscriptions) { | |
// Add the computation to the subscriptions set | |
subscriptions.add(running); | |
// Add the subscriptions set to the dependencies of the computation | |
running.dependencies.add(subscriptions); | |
} | |
// Function to create a signal with a given initial value | |
function createSignal(value) { | |
// Set to store the computations subscribed to the signal | |
const subscriptions = new Set(); | |
// Function to read the current value of the signal | |
const read = () => { | |
// Get the currently executing computation (if any) | |
const running = context[context.length - 1]; | |
// If there's a running computation, subscribe it to the signal's subscriptions | |
if (running) subscribe(running, subscriptions); | |
// Return the current value of the signal | |
return value; | |
}; | |
// Function to update the value of the signal | |
const write = (nextValue) => { | |
// Update the value of the signal | |
value = nextValue; | |
// Iterate over the subscriptions and execute each one | |
for (const sub of [...subscriptions]) { | |
sub.execute(); | |
} | |
}; | |
// Return a tuple containing the read and write functions | |
return [read, write]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment