-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path3-naïve-closure.js
More file actions
38 lines (27 loc) · 830 Bytes
/
3-naïve-closure.js
File metadata and controls
38 lines (27 loc) · 830 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
'use strict';
const signal = (value) => {
const box = { value };
const getter = () => {
if (typeof box.value !== 'function') return box.value;
return box.value();
};
getter.set = (value) => (box.value = value);
getter.update = (callback) => (box.value = callback(box.value));
return getter;
};
const computed = (compute) => signal(compute);
// Usage
const count = signal(100);
console.log(`Count 1: ${count()}`);
count.set(200);
console.log(`Count 2: ${count()}`);
count.update((prev) => prev + 50);
console.log(`Count 3: ${count()}`);
const num = signal(1000);
console.log(`Num 1: ${num()}`);
const total = computed(() => num() + count());
console.log(`Total 1: ${total()}`);
// Display reactivity
num.update((prev) => prev * 2);
console.log(`Num 2: ${num()}`);
console.log(`Total 2: ${total()}`);