Skip to content

Instantly share code, notes, and snippets.

@lappi-lynx
Created August 14, 2024 11:19
Show Gist options
  • Save lappi-lynx/a5d87b062f7d4168340bfcdfcfcc3dd2 to your computer and use it in GitHub Desktop.
Save lappi-lynx/a5d87b062f7d4168340bfcdfcfcc3dd2 to your computer and use it in GitHub Desktop.
js signal simple implementation
const signal = (value) => {
const box = { value };
const getter = () => {
if (typeof box.value !== 'function') {
return box.value;
}
return box.value();
};
getter.set = (newValue) => { box.value = newValue };
getter.update = (callback) => { box.value = callback(box.value) };
return getter;
};
const computed = (compute) => signal(compute);
// Usage examples for signal and computed
// Example 1: Basic signal usage
const count = signal(0);
console.log(count()); // Output: 0
count.set(5);
console.log(count()); // Output: 5
count.update(val => val + 1);
console.log(count()); // Output: 6
// Example 2: Signal with object
const user = signal({ name: 'John', age: 30 });
console.log(user().name); // Output: John
user.update(u => ({ ...u, age: u.age + 1 }));
console.log(user().age); // Output: 31
// Example 3: Computed signal
const celsius = signal(0);
const fahrenheit = computed(() => celsius() * 9/5 + 32);
console.log(fahrenheit()); // Output: 32
celsius.set(100);
console.log(fahrenheit()); // Output: 212
// Example 4: Nested computations
const a = signal(1);
const b = signal(2);
const sum = computed(() => a() + b());
const double = computed(() => sum() * 2);
console.log(double()); // Output: 6
a.set(3);
console.log(double()); // Output: 10
// Example 5: Signal with function value
const greet = signal(() => "Hello, World!");
console.log(greet()); // Output: Hello, World!
greet.set(() => "Bonjour, le monde!");
console.log(greet()); // Output: Bonjour, le monde!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment