Complete the code to create a writable store in Svelte.
import { [1] } from 'svelte/store'; const count = [1](0);
The writable function creates a store that can be updated and subscribed to.
Complete the code to define a custom store with a subscribe method.
function createCounter() {
let count = 0;
const subscribers = [];
function subscribe(run) {
subscribers.push(run);
run(count);
return () => {
subscribers.splice(subscribers.indexOf(run), 1);
};
}
return { subscribe, [1] };
}The custom store returns a subscribe method and a custom increment method to change the value.
Fix the error in the increment method to notify subscribers.
function createCounter() {
let count = 0;
const subscribers = [];
function subscribe(run) {
subscribers.push(run);
run(count);
return () => {
subscribers.splice(subscribers.indexOf(run), 1);
};
}
function increment() {
count += 1;
subscribers.forEach(run => run([1]));
}
return { subscribe, increment };
}We call each subscriber function with the updated count value to notify them.
Fill both blanks to create a custom store with a reset method.
function createCounter() {
let count = 0;
const subscribers = [];
function subscribe(run) {
subscribers.push(run);
run(count);
return () => {
subscribers.splice(subscribers.indexOf(run), 1);
};
}
function increment() {
count += 1;
subscribers.forEach(run => run([1]));
}
function reset() {
count = [2];
subscribers.forEach(run => run(count));
}
return { subscribe, increment, reset };
}The increment method sends the updated count. The reset method sets count to zero.
Fill all three blanks to create a custom store with subscribe, increment, and decrement methods.
function createCounter() {
let count = 0;
const subscribers = [];
function subscribe(run) {
subscribers.push(run);
run(count);
return () => {
subscribers.splice(subscribers.indexOf(run), 1);
};
}
function increment() {
count += 1;
subscribers.forEach(run => run([1]));
}
function decrement() {
count -= 1;
subscribers.forEach(run => run([2]));
}
function reset() {
count = [3];
subscribers.forEach(run => run(count));
}
return { subscribe, increment, decrement, reset };
}Both increment and decrement notify subscribers with the updated count. The reset method sets count to zero.