UNPKG

1.95 kBJavaScriptView Raw
1import { valid, nullish } from '@typen/nullish';
2
3class Chore {
4 fn;
5 #n;
6 #arg;
7 ctx;
8
9 constructor(fn, mode) {
10 this.fn = fn;
11 this.mode = valid(mode) ? mode : fn.length;
12 }
13
14 static build(fn, arg, ctx, mode) {
15 const method = new Chore(fn, mode);
16 if (valid(arg)) method.arg = arg;
17 if (valid(ctx)) method.ctx = ctx;
18 return method;
19 }
20
21 static create({
22 fn,
23 arg,
24 ctx,
25 mode
26 }) {
27 return Chore.build(fn, arg, ctx, mode);
28 }
29
30 get mode() {
31 return this.#n;
32 }
33
34 set mode(n) {
35 this.#n = n; // const prevN = this.#n
36
37 if (n === 0) return this.#arg = null, n; // if (n === 1) return this.#arg = arg
38
39 const arg = this.#arg;
40 if (valid(arg) && n >= 2 && !Array.isArray(arg)) this.#arg = [arg];
41 return n;
42 }
43
44 get arg() {
45 return this.#arg;
46 }
47
48 set arg(val) {
49 const n = this.#n;
50 if (n === 0) return this.#arg = val;
51 if (n === 1) return this.#arg = val;
52 if (n >= 2) return this.#arg = Array.isArray(val) ? val : [val];
53 }
54
55 get caller() {
56 const {
57 mode,
58 fn,
59 ctx,
60 arg
61 } = this;
62 return valid(ctx) ? nullish(arg) ? fn.bind(ctx) // || mode === 0 ?
63 : mode === 1 || !Array.isArray(arg) ? fn.bind(ctx, arg) : fn.bind(ctx, ...arg) : nullish(arg) ? fn // || mode === 0 ?
64 : mode === 1 || !Array.isArray(arg) ? () => fn(arg) : () => fn(...arg);
65 }
66
67 set caller(fn) {
68 this.fn = fn;
69 if (nullish(this.mode)) this.mode = this.fn.length;
70 }
71
72 get context() {
73 return this.ctx;
74 }
75
76 set context(ctx) {
77 return this.ctx = ctx;
78 }
79
80 invoke(arg) {
81 arg = arg ?? this.arg;
82 const {
83 mode,
84 ctx,
85 fn
86 } = this;
87 return valid(ctx) ? nullish(arg) ? fn.call(ctx) // || mode === 0 ?
88 : mode === 1 || !Array.isArray(arg) ? fn.call(ctx, arg) : fn.apply(ctx, arg) : nullish(arg) ? fn() // || mode === 0 ?
89 : mode === 1 || !Array.isArray(arg) ? fn(arg) : fn(...arg);
90 }
91
92}
93
94export { Chore };