repos / starfx

supercharged async flow control library.
git clone https://github.com/neurosnap/starfx.git

starfx / store / slice
Vlad · 29 Jul 23

num.ts

 1import type { AnyState } from "../../types.ts";
 2
 3import type { BaseSchema } from "../types.ts";
 4
 5export interface NumOutput<S extends AnyState> extends BaseSchema<number> {
 6  schema: "num";
 7  initialState: number;
 8  set: (v: number) => (s: S) => void;
 9  increment: (by?: number) => (s: S) => void;
10  decrement: (by?: number) => (s: S) => void;
11  reset: () => (s: S) => void;
12  select: (s: S) => number;
13}
14
15export function createNum<S extends AnyState = AnyState>(
16  { name, initialState = 0 }: { name: keyof S; initialState?: number },
17): NumOutput<S> {
18  return {
19    name: name as string,
20    schema: "num",
21    initialState,
22    set: (value) => (state) => {
23      // deno-lint-ignore no-explicit-any
24      (state as any)[name] = value;
25    },
26    increment: (by = 1) => (state) => {
27      // deno-lint-ignore no-explicit-any
28      (state as any)[name] += by;
29    },
30    decrement: (by = 1) => (state) => {
31      // deno-lint-ignore no-explicit-any
32      (state as any)[name] -= by;
33    },
34    reset: () => (state) => {
35      // deno-lint-ignore no-explicit-any
36      (state as any)[name] = initialState;
37    },
38    select: (state) => {
39      // deno-lint-ignore no-explicit-any
40      return (state as any)[name];
41    },
42  };
43}
44
45export function num(initialState?: number) {
46  return (name: string) => createNum<AnyState>({ name, initialState });
47}