Skip to content

Instantly share code, notes, and snippets.

@stenin-nikita
Created November 12, 2020 18:27
Show Gist options
  • Save stenin-nikita/e7754e3504c1cf146e98f8dd095b53cb to your computer and use it in GitHub Desktop.
Save stenin-nikita/e7754e3504c1cf146e98f8dd095b53cb to your computer and use it in GitHub Desktop.
export interface Fn<Args extends any[] = [], Result = void> {
(...args: Args): Result;
}
export type Getter<T> = Fn<[track: Track], T>;
export type Setter<T> = Fn<[value: T], void>;
export type Updater<T> = Fn<[reducer: Fn<[value: T], T>], void>;
export interface Atom<T> {
set: Setter<T>;
update: Updater<T>;
}
export interface Track {
<T>(atom: Atom<T>): T;
}
export interface ComputedAtomOptions<T> {
get: Getter<T>;
set?: Setter<T>;
}
export function computed<T>(
getterOrOptions: ComputedAtomOptions<T> | Getter<T>
): Atom<T> {
return {} as any;
}
export function atom<T = undefined>(): Atom<T | undefined>;
export function atom<T>(initialValue: T): Atom<T>;
export function atom<T>(initialValue?: T): Atom<T | undefined> {
return {} as any;
}
// Public API
declare const context: any;
const firstNameAtom = atom('John');
const lastNameAtom = atom('Doe');
const fullNameAtom = computed<string>({
get: track => `${track(firstNameAtom)} ${track(lastNameAtom)}`,
set: fullName => {
const [firstName, lastName] = fullName.split(' ');
firstNameAtom.set(firstName);
lastNameAtom.set(lastName);
},
});
const isFirstNameShortAtom = computed(
track => track(firstNameAtom).length < 10
);
const displayNameAtom = computed(track => {
return track(isFirstNameShortAtom)
? track(fullNameAtom)
: track(firstNameAtom);
});
context.subscribe(displayNameAtom, v => {
v; //?
});
context.runIn(() => firstNameAtom.set('John'));
context.runIn(() => firstNameAtom.update(prevValue => 'John'));
context.runIn(() => fullNameAtom.set('Joooooooooooooe Doe'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment