Skip to content

Instantly share code, notes, and snippets.

@helabenkhalfallah
Created April 28, 2024 09:41
Show Gist options
  • Save helabenkhalfallah/fdc3249154d825a1f85faea924f10007 to your computer and use it in GitHub Desktop.
Save helabenkhalfallah/fdc3249154d825a1f85faea924f10007 to your computer and use it in GitHub Desktop.
Simplified internal implementation of the interaction between the "signal" and the "dependency graph"
class Signal {
constructor(initialValue, dependencyGraph) {
this.value = initialValue;
this.dependencyGraph = dependencyGraph;
}
// Method to set a new value and notify subscribers
setValue(newValue) {
this.value = newValue;
// Notify subscribers through the dependency graph
this.dependencyGraph.notify(this, newValue);
}
}
class DependencyGraph {
constructor() {
this.dependencies = new Map();
}
// Method to add a dependency between a signal and a subscriber
addDependency(signal, subscriber) {
if (!this.dependencies.has(signal)) {
this.dependencies.set(signal, new Set());
}
this.dependencies.get(signal).add(subscriber);
}
// Method to remove a dependency between a signal and a subscriber
removeDependency(signal, subscriber) {
if (this.dependencies.has(signal)) {
this.dependencies.get(signal).delete(subscriber);
}
}
// Method to notify subscribers of a signal with its new value
notify(signal, newValue) {
if (this.dependencies.has(signal)) {
// Notify all subscribers of the signal with the new value
this.dependencies.get(signal).forEach(subscriber => subscriber(newValue));
}
}
}
// Example usage
const dependencyGraph = new DependencyGraph();
// Create signals with the dependency graph
const signal1 = new Signal("Initial Value 1", dependencyGraph);
const signal2 = new Signal("Initial Value 2", dependencyGraph);
// Adding dependencies
dependencyGraph.addDependency(signal1, newValue => console.log("Subscriber 1:", newValue));
dependencyGraph.addDependency(signal2, newValue => console.log("Subscriber 2:", newValue));
// Setting new values
signal1.setValue("New Value 1");
signal2.setValue("New Value 2");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment