@adriansteffan/reactive 0.0.27 → 0.0.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,46 +3,52 @@ declare global {
3
3
  /**
4
4
  * Returns random elements from the array
5
5
  * @param n Number of random elements to return (defaults to 1)
6
- * @returns Array of randomly selected elements
7
6
  */
8
7
  sample(n?: number): Array<T>;
9
-
8
+
10
9
  /**
11
10
  * Shuffles array elements using Fisher-Yates algorithm
12
- * @returns A new shuffled array
13
11
  */
14
12
  shuffle(): Array<T>;
13
+
14
+ /**
15
+ * Applies a function to the array
16
+ * @param fn Function to apply to the array
17
+ */
18
+ pipe<U>(fn: (arr: Array<T>) => U): U;
19
+
20
+ /**
21
+ * Splits array into chunks
22
+ * @param n Number of chunks to create
23
+ */
24
+ chunk(n: number): Array<Array<T>>;
15
25
  }
16
26
  }
17
27
 
18
28
  /**
19
29
  * Returns random elements from an array
20
- * @param array The source array
21
- * @param n Number of random elements to return (defaults to 1)
22
- * @returns Array of randomly selected elements
23
30
  */
24
31
  export function sample<T>(array: T[], n: number = 1): T[] {
25
32
  const result: T[] = [];
26
-
33
+
27
34
  if (array.length === 0) {
28
35
  return result;
29
36
  }
30
-
37
+
31
38
  for (let i = 0; i < n; i++) {
32
39
  const randomIndex = Math.floor(Math.random() * array.length);
33
40
  result.push(array[randomIndex]);
34
41
  }
35
-
42
+
36
43
  return result;
37
44
  }
38
45
 
39
46
  /**
40
47
  * Shuffles array elements using Fisher-Yates algorithm
41
- * @param array The source array
42
- * @returns A new shuffled array
43
48
  */
44
49
  export function shuffle<T>(array: T[]): T[] {
45
- const result = [...array];
50
+ const result = [...array];
51
+
46
52
  for (let i = result.length - 1; i >= 0; i--) {
47
53
  const j = Math.floor(Math.random() * (i + 1));
48
54
  [result[i], result[j]] = [result[j], result[i]];
@@ -50,6 +56,23 @@ export function shuffle<T>(array: T[]): T[] {
50
56
  return result;
51
57
  }
52
58
 
59
+ /**
60
+ * Applies a function to an array
61
+ */
62
+ export function pipe<T, U>(array: T[], fn: (arr: T[]) => U): U {
63
+ return fn(array);
64
+ }
65
+
66
+ /**
67
+ * Splits array into chunks
68
+ */
69
+ export function chunk<T>(array: T[], n: number): T[][] {
70
+ const size = Math.ceil(array.length / n);
71
+ return Array.from({ length: Math.ceil(array.length / size) }, (_, i) =>
72
+ array.slice(i * size, i * size + size),
73
+ );
74
+ }
75
+
53
76
  /**
54
77
  * Registers array methods on the Array prototype.
55
78
  * Call this function once to make array methods available globally.
@@ -59,7 +82,6 @@ export function shuffle<T>(array: T[]): T[] {
59
82
  * import { registerArrayExtensions } from '@adriansteffan/reactive/array';
60
83
  * registerArrayExtensions();
61
84
  *
62
- * // Now you can use the methods
63
85
  * const myArray = [1, 2, 3, 4, 5];
64
86
  * myArray.shuffle();
65
87
  * ```
@@ -70,10 +92,22 @@ export function registerArrayExtensions(): void {
70
92
  return sample(this, n);
71
93
  };
72
94
  }
73
-
95
+
74
96
  if (typeof Array.prototype.shuffle !== 'function') {
75
97
  Array.prototype.shuffle = function <T>(this: T[]): T[] {
76
- return shuffle(this);
98
+ return shuffle(this);
99
+ };
100
+ }
101
+
102
+ if (typeof Array.prototype.pipe !== 'function') {
103
+ Array.prototype.pipe = function <T, U>(this: T[], fn: (arr: T[]) => U): U {
104
+ return pipe(this, fn);
105
+ };
106
+ }
107
+
108
+ if (typeof Array.prototype.chunk !== 'function') {
109
+ Array.prototype.chunk = function <T>(this: T[], n: number): T[][] {
110
+ return chunk(this, n);
77
111
  };
78
112
  }
79
113
  }
@@ -1,178 +1,209 @@
1
1
  export type Store = Record<string, any>;
2
2
 
3
3
  type BaseTrialData = {
4
- index: number;
5
- trialNumber: number;
6
- start: number;
7
- end: number;
8
- duration: number;
4
+ index: number;
5
+ trialNumber: number;
6
+ start: number;
7
+ end: number;
8
+ duration: number;
9
9
  };
10
10
 
11
11
  export type ComponentResultData = BaseTrialData & {
12
- type: string;
13
- name: string;
14
- responseData?: any;
12
+ type: string;
13
+ name: string;
14
+ responseData?: any;
15
+ metadata?: Record<string, any>;
15
16
  };
16
17
 
17
18
  export type CanvasResultData = BaseTrialData & {
18
- metadata?: Record<string, any>;
19
- key: string | null;
20
- reactionTime: number | null;
19
+ metadata?: Record<string, any>;
20
+ key: string | null;
21
+ reactionTime: number | null;
21
22
  };
22
23
 
23
24
  export type RefinedTrialData = ComponentResultData | CanvasResultData;
24
25
 
25
- export interface MarkerItem { type: 'MARKER'; id: string; }
26
+ export interface MarkerItem {
27
+ type: 'MARKER';
28
+ id: string;
29
+ }
26
30
 
27
31
  export type ConditionalFunction = (data?: RefinedTrialData[], store?: Store) => boolean;
28
32
 
29
33
  export type StoreUpdateFunction = (data?: RefinedTrialData[], store?: Store) => Record<string, any>;
30
34
 
31
- export interface IfGotoItem { type: 'IF_GOTO'; cond: ConditionalFunction; marker: string; }
32
- export interface UpdateStoreItem { type: 'UPDATE_STORE'; fun: StoreUpdateFunction; }
33
- export interface IfBlockItem { type: 'IF_BLOCK'; cond: ConditionalFunction; timeline: TimelineItem[]; }
34
- export interface WhileBlockItem { type: 'WHILE_BLOCK'; cond: ConditionalFunction; timeline: TimelineItem[]; }
35
- export type ControlFlowItem = MarkerItem | IfGotoItem | UpdateStoreItem | IfBlockItem | WhileBlockItem;
35
+ export interface IfGotoItem {
36
+ type: 'IF_GOTO';
37
+ cond: ConditionalFunction;
38
+ marker: string;
39
+ }
40
+ export interface UpdateStoreItem {
41
+ type: 'UPDATE_STORE';
42
+ fun: StoreUpdateFunction;
43
+ }
44
+ export interface IfBlockItem {
45
+ type: 'IF_BLOCK';
46
+ cond: ConditionalFunction;
47
+ timeline: TimelineItem[];
48
+ }
49
+ export interface WhileBlockItem {
50
+ type: 'WHILE_BLOCK';
51
+ cond: ConditionalFunction;
52
+ timeline: TimelineItem[];
53
+ }
54
+ export type ControlFlowItem =
55
+ | MarkerItem
56
+ | IfGotoItem
57
+ | UpdateStoreItem
58
+ | IfBlockItem
59
+ | WhileBlockItem;
36
60
  export type TimelineItem = ControlFlowItem | any;
37
61
 
38
- export interface ExecuteContentInstruction { type: 'ExecuteContent'; content: any; }
62
+ export interface ExecuteContentInstruction {
63
+ type: 'ExecuteContent';
64
+ content: any;
65
+ }
39
66
  export interface IfGotoInstruction {
40
- type: 'IfGoto';
41
- cond: (store: Store, data: RefinedTrialData[]) => boolean;
42
- marker: string;
67
+ type: 'IfGoto';
68
+ cond: (store: Store, data: RefinedTrialData[]) => boolean;
69
+ marker: string;
43
70
  }
44
71
  export interface UpdateStoreInstruction {
45
- type: 'UpdateStore';
46
- fun: (store: Store, data: RefinedTrialData[]) => Store;
72
+ type: 'UpdateStore';
73
+ fun: (store: Store, data: RefinedTrialData[]) => Store;
47
74
  }
48
- export type UnifiedBytecodeInstruction = ExecuteContentInstruction | IfGotoInstruction | UpdateStoreInstruction;
75
+ export type UnifiedBytecodeInstruction =
76
+ | ExecuteContentInstruction
77
+ | IfGotoInstruction
78
+ | UpdateStoreInstruction;
49
79
 
50
80
  function prefixUserMarkers(marker: string): string {
51
- return `user_${marker}`;
81
+ return `user_${marker}`;
52
82
  }
53
83
 
54
- export function compileTimeline(
55
- timeline: TimelineItem[]
56
- ): {
57
- instructions: UnifiedBytecodeInstruction[];
58
- markers: { [key: string]: number };
84
+ export function compileTimeline(timeline: TimelineItem[]): {
85
+ instructions: UnifiedBytecodeInstruction[];
86
+ markers: { [key: string]: number };
59
87
  } {
60
- const instructions: UnifiedBytecodeInstruction[] = [];
61
- const markers: { [key: string]: number } = {};
62
- let uniqueMarkerCounterForThisRun = 0;
63
-
64
- function getUniqueMarker(prefix: string): string {
65
- return `${prefix}_auto_${uniqueMarkerCounterForThisRun++}`;
66
- }
67
-
68
- function adaptCondition(
69
- userCondition: ConditionalFunction
70
- ): (store: Store, data: RefinedTrialData[]) => boolean {
71
- return (runtimeStore: Store, runtimeData: RefinedTrialData[]): boolean => {
72
- return userCondition(runtimeData, runtimeStore);
73
- };
74
- }
75
-
76
- function adaptUpdate(
77
- userUpdateFunction: StoreUpdateFunction
78
- ): (store: Store, data: RefinedTrialData[]) => Store {
79
- return (runtimeStore: Store, runtimeData: RefinedTrialData[]): Store => {
80
- const updates = userUpdateFunction(runtimeData, runtimeStore);
81
- if (typeof updates === 'object' && updates !== null) {
82
- return {
83
- ...runtimeStore,
84
- ...updates,
85
- };
86
- } else {
87
- console.warn("Store update function did not return an object. Store remains unchanged.", { data: runtimeData, store: runtimeStore });
88
- return runtimeStore;
89
- }
88
+ const instructions: UnifiedBytecodeInstruction[] = [];
89
+ const markers: { [key: string]: number } = {};
90
+ let uniqueMarkerCounterForThisRun = 0;
91
+
92
+ function getUniqueMarker(prefix: string): string {
93
+ return `${prefix}_auto_${uniqueMarkerCounterForThisRun++}`;
94
+ }
95
+
96
+ function adaptCondition(
97
+ userCondition: ConditionalFunction,
98
+ ): (store: Store, data: RefinedTrialData[]) => boolean {
99
+ return (runtimeStore: Store, runtimeData: RefinedTrialData[]): boolean => {
100
+ return userCondition(runtimeData, runtimeStore);
101
+ };
102
+ }
103
+
104
+ function adaptUpdate(
105
+ userUpdateFunction: StoreUpdateFunction,
106
+ ): (store: Store, data: RefinedTrialData[]) => Store {
107
+ return (runtimeStore: Store, runtimeData: RefinedTrialData[]): Store => {
108
+ const updates = userUpdateFunction(runtimeData, runtimeStore);
109
+ if (typeof updates === 'object' && updates !== null) {
110
+ return {
111
+ ...runtimeStore,
112
+ ...updates,
90
113
  };
91
- }
92
-
93
- function processTimeline(items: TimelineItem[]) {
94
- for (const item of items) {
95
- let isControlFlow = false;
96
-
97
- if (typeof item === 'object' && item !== null && 'type' in item) {
98
- const itemType = item.type;
99
-
100
- switch (itemType) {
101
- case 'MARKER': {
102
- const markerItem = item as MarkerItem;
103
- markers[prefixUserMarkers(markerItem.id)] = instructions.length;
104
- isControlFlow = true;
105
- break;
106
- }
107
- case 'IF_GOTO': {
108
- const ifGotoItem = item as IfGotoItem;
109
- const runtimeConditionFunc = adaptCondition(ifGotoItem.cond);
110
- instructions.push({
111
- type: 'IfGoto',
112
- cond: runtimeConditionFunc,
113
- marker: prefixUserMarkers(ifGotoItem.marker),
114
- });
115
- isControlFlow = true;
116
- break;
117
- }
118
- case 'UPDATE_STORE': {
119
- const updateStoreItem = item as UpdateStoreItem;
120
- const runtimeUpdateFunc = adaptUpdate(updateStoreItem.fun);
121
- instructions.push({
122
- type: 'UpdateStore',
123
- fun: runtimeUpdateFunc,
124
- });
125
- isControlFlow = true;
126
- break;
127
- }
128
- case 'IF_BLOCK': {
129
- const ifBlockItem = item as IfBlockItem;
130
- const endMarker = getUniqueMarker('if_end');
131
- const runtimeConditionFunc = adaptCondition(ifBlockItem.cond);
132
- instructions.push({
133
- type: 'IfGoto',
134
- cond: (store, data) => !runtimeConditionFunc(store, data),
135
- marker: endMarker,
136
- });
137
- processTimeline(ifBlockItem.timeline);
138
- markers[endMarker] = instructions.length;
139
- isControlFlow = true;
140
- break;
141
- }
142
- case 'WHILE_BLOCK': {
143
- const whileBlockItem = item as WhileBlockItem;
144
- const startMarker = getUniqueMarker('while_start');
145
- const endMarker = getUniqueMarker('while_end');
146
- const runtimeConditionFunc = adaptCondition(whileBlockItem.cond);
147
- markers[startMarker] = instructions.length;
148
- instructions.push({
149
- type: 'IfGoto',
150
- cond: (store, data) => !runtimeConditionFunc(store, data),
151
- marker: endMarker,
152
- });
153
- processTimeline(whileBlockItem.timeline);
154
- instructions.push({
155
- type: 'IfGoto',
156
- cond: () => true,
157
- marker: startMarker,
158
- });
159
- markers[endMarker] = instructions.length;
160
- isControlFlow = true;
161
- break;
162
- }
163
- }
164
- }
165
-
166
- if (!isControlFlow) {
167
- instructions.push({
168
- type: 'ExecuteContent',
169
- content: item,
170
- });
171
- }
114
+ } else {
115
+ console.warn('Store update function did not return an object. Store remains unchanged.', {
116
+ data: runtimeData,
117
+ store: runtimeStore,
118
+ });
119
+ return runtimeStore;
120
+ }
121
+ };
122
+ }
123
+
124
+ function processTimeline(items: TimelineItem[]) {
125
+ for (const item of items) {
126
+ let isControlFlow = false;
127
+
128
+ if (typeof item === 'object' && item !== null && 'type' in item) {
129
+ const itemType = item.type;
130
+
131
+ switch (itemType) {
132
+ case 'MARKER': {
133
+ const markerItem = item as MarkerItem;
134
+ markers[prefixUserMarkers(markerItem.id)] = instructions.length;
135
+ isControlFlow = true;
136
+ break;
137
+ }
138
+ case 'IF_GOTO': {
139
+ const ifGotoItem = item as IfGotoItem;
140
+ const runtimeConditionFunc = adaptCondition(ifGotoItem.cond);
141
+ instructions.push({
142
+ type: 'IfGoto',
143
+ cond: runtimeConditionFunc,
144
+ marker: prefixUserMarkers(ifGotoItem.marker),
145
+ });
146
+ isControlFlow = true;
147
+ break;
148
+ }
149
+ case 'UPDATE_STORE': {
150
+ const updateStoreItem = item as UpdateStoreItem;
151
+ const runtimeUpdateFunc = adaptUpdate(updateStoreItem.fun);
152
+ instructions.push({
153
+ type: 'UpdateStore',
154
+ fun: runtimeUpdateFunc,
155
+ });
156
+ isControlFlow = true;
157
+ break;
158
+ }
159
+ case 'IF_BLOCK': {
160
+ const ifBlockItem = item as IfBlockItem;
161
+ const endMarker = getUniqueMarker('if_end');
162
+ const runtimeConditionFunc = adaptCondition(ifBlockItem.cond);
163
+ instructions.push({
164
+ type: 'IfGoto',
165
+ cond: (store, data) => !runtimeConditionFunc(store, data),
166
+ marker: endMarker,
167
+ });
168
+ processTimeline(ifBlockItem.timeline);
169
+ markers[endMarker] = instructions.length;
170
+ isControlFlow = true;
171
+ break;
172
+ }
173
+ case 'WHILE_BLOCK': {
174
+ const whileBlockItem = item as WhileBlockItem;
175
+ const startMarker = getUniqueMarker('while_start');
176
+ const endMarker = getUniqueMarker('while_end');
177
+ const runtimeConditionFunc = adaptCondition(whileBlockItem.cond);
178
+ markers[startMarker] = instructions.length;
179
+ instructions.push({
180
+ type: 'IfGoto',
181
+ cond: (store, data) => !runtimeConditionFunc(store, data),
182
+ marker: endMarker,
183
+ });
184
+ processTimeline(whileBlockItem.timeline);
185
+ instructions.push({
186
+ type: 'IfGoto',
187
+ cond: () => true,
188
+ marker: startMarker,
189
+ });
190
+ markers[endMarker] = instructions.length;
191
+ isControlFlow = true;
192
+ break;
193
+ }
172
194
  }
195
+ }
196
+
197
+ if (!isControlFlow) {
198
+ instructions.push({
199
+ type: 'ExecuteContent',
200
+ content: item,
201
+ });
202
+ }
173
203
  }
204
+ }
174
205
 
175
- processTimeline(timeline);
206
+ processTimeline(timeline);
176
207
 
177
- return { instructions, markers };
178
- }
208
+ return { instructions, markers };
209
+ }