Skip to content

Instantly share code, notes, and snippets.

@akku1139
Created March 1, 2025 15:18
Show Gist options
  • Save akku1139/02ae36b7da593f6e20cae37349d7b042 to your computer and use it in GitHub Desktop.
Save akku1139/02ae36b7da593f6e20cae37349d7b042 to your computer and use it in GitHub Desktop.
GeminiにcreateSignal作らせた
function createSignal(value) {
const subscribers = new Set();
const read = () => {
if (currentComponent) {
subscribers.add(currentComponent);
}
return value;
};
const write = (newValue) => {
if (value !== newValue) {
value = newValue;
subscribers.forEach((subscriber) => subscriber());
}
};
return [read, write];
}
let currentComponent = null;
function effect(fn) {
currentComponent = fn;
fn();
currentComponent = null;
}
document.body.innerHTML = `
<div id="count"></div>
<button id="up">Increment</button>
`;
const [count, setCount] = createSignal(0);
effect(() => {
document.getElementById("count").textContent = `Count: ${count()}`;
});
document.getElementById("up").addEventListener("click",() => {
setCount(count() + 1);
})
function createSignal<T>(initialValue: T): [() => T, (newValue: T) => void, (subscriber: () => void) => void] {
let value = initialValue;
const subscribers = new Set<() => void>();
const read = () => {
return value;
};
const write = (newValue: T) => {
value = newValue;
subscribers.forEach((subscriber) => subscriber());
};
const subscribe = (subscriber: () => void) => {
subscribers.add(subscriber);
};
return [read, write, subscribe];
}
const [count, setCount, subscribeCount] = createSignal(0);
subscribeCount(() => {
console.log("Count changed:", count());
});
setCount(1); // "Count changed: 1" と出力される
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment