0
# Helper Functions
1
2
Utility functions for working with observables, including type checking, object manipulation, and path operations. These functions provide essential utilities for advanced observable usage and integration.
3
4
## Capabilities
5
6
### Observable Utilities
7
8
Functions for working with and manipulating observables.
9
10
```typescript { .api }
11
/**
12
* Checks if a value is an observable
13
* @param value - Value to check
14
* @returns True if value is observable
15
*/
16
function isObservable(value: any): boolean;
17
18
/**
19
* Checks if an observable value is ready (not loading/pending)
20
* @param value - Observable value to check
21
* @returns True if value is ready
22
*/
23
function isObservableValueReady(value: any): boolean;
24
25
/**
26
* Locks or unlocks an observable to prevent/allow modifications
27
* @param obs - Observable to lock/unlock
28
* @param locked - Whether to lock (true) or unlock (false)
29
*/
30
function lockObservable(obs: Observable<any>, locked: boolean): void;
31
32
/**
33
* Sets a value in an observable without triggering change notifications
34
* @param obs - Observable to update
35
* @param value - New value to set
36
*/
37
function setSilently<T>(obs: Observable<T>, value: T): void;
38
39
/**
40
* Merges multiple source objects into a target observable
41
* @param target - Target observable to merge into
42
* @param sources - Source objects to merge from
43
*/
44
function mergeIntoObservable<T>(
45
target: Observable<T>,
46
...sources: Partial<T>[]
47
): void;
48
49
/**
50
* Gets the internal index of an observable for advanced use cases
51
* @param obs - Observable to get index for
52
* @returns Internal index number
53
*/
54
function getObservableIndex(obs: Observable<any>): number;
55
```
56
57
### Path Operations
58
59
Functions for working with object paths and nested property access.
60
61
```typescript { .api }
62
/**
63
* Sets a value at a specific path in an object
64
* @param obj - Object to modify
65
* @param path - Path as array of property names
66
* @param value - Value to set at path
67
*/
68
function setAtPath(obj: object, path: string[], value: any): void;
69
70
/**
71
* Sets a value at a specific path within an observable
72
* @param obs - Observable to modify
73
* @param path - Path as array of property names
74
* @param value - Value to set at path
75
*/
76
function setInObservableAtPath(
77
obs: Observable<any>,
78
path: string[],
79
value: any
80
): void;
81
82
/**
83
* Constructs an object with a value at a specific path
84
* @param obj - Base object to extend
85
* @param path - Path where to place the value
86
* @param value - Value to place at path
87
* @returns New object with value at path
88
*/
89
function constructObjectWithPath(
90
obj: object,
91
path: string[],
92
value: any
93
): object;
94
95
/**
96
* Extracts a value from an object at a specific path
97
* @param obj - Object to extract from
98
* @param path - Path to extract value from
99
* @returns Value at the specified path
100
*/
101
function deconstructObjectWithPath(obj: object, path: string[]): any;
102
```
103
104
### Selector Utilities
105
106
Functions for working with selectors and computed values.
107
108
```typescript { .api }
109
/**
110
* Computes the value of a selector function
111
* @param selector - Selector function to compute
112
* @returns Computed value from selector
113
*/
114
function computeSelector<T>(selector: () => T): T;
115
```
116
117
### Object Utilities
118
119
Functions for creating special object types and wrappers.
120
121
```typescript { .api }
122
/**
123
* Creates an opaque object wrapper that prevents direct property access
124
* @param obj - Object to make opaque
125
* @returns Opaque wrapped object
126
*/
127
function opaqueObject<T>(obj: T): OpaqueObject<T>;
128
129
interface OpaqueObject<T> extends Observable<T> {
130
/** Opaque objects can only be accessed through observable methods */
131
}
132
```
133
134
### Type Checking Functions
135
136
Utility functions for runtime type checking and validation.
137
138
```typescript { .api }
139
/**
140
* Checks if object has own property (not inherited)
141
* @param obj - Object to check
142
* @param prop - Property name to check for
143
* @returns True if object has own property
144
*/
145
function hasOwnProperty(obj: object, prop: string): boolean;
146
147
/**
148
* Checks if value is an array
149
* @param value - Value to check
150
* @returns True if value is array
151
*/
152
function isArray(value: any): value is Array<any>;
153
154
/**
155
* Checks if value is a Date object
156
* @param value - Value to check
157
* @returns True if value is Date
158
*/
159
function isDate(value: any): value is Date;
160
161
/**
162
* Checks if value is a boolean
163
* @param value - Value to check
164
* @returns True if value is boolean
165
*/
166
function isBoolean(value: any): value is boolean;
167
168
/**
169
* Checks if value is empty (null, undefined, empty string, empty array, empty object)
170
* @param value - Value to check
171
* @returns True if value is empty
172
*/
173
function isEmpty(value: any): boolean;
174
175
/**
176
* Checks if value is a function
177
* @param value - Value to check
178
* @returns True if value is function
179
*/
180
function isFunction(value: any): value is Function;
181
182
/**
183
* Checks if value is an object (not null, not array, not function)
184
* @param value - Value to check
185
* @returns True if value is object
186
*/
187
function isObject(value: any): value is Record<any, any>;
188
189
/**
190
* Checks if value is a primitive type (string, number, boolean, null, undefined, symbol)
191
* @param value - Value to check
192
* @returns True if value is primitive
193
*/
194
function isPrimitive(value: any): value is string | number | bigint | boolean | symbol;
195
196
/**
197
* Checks if value is a Promise
198
* @param value - Value to check
199
* @returns True if value is Promise
200
*/
201
function isPromise<T>(value: any): value is Promise<T>;
202
203
/**
204
* Checks if value is a string
205
* @param value - Value to check
206
* @returns True if value is string
207
*/
208
function isString(value: any): value is string;
209
210
/**
211
* Checks if value is a symbol
212
* @param value - Value to check
213
* @returns True if value is symbol
214
*/
215
function isSymbol(value: any): value is symbol;
216
```
217
218
### Time Utilities
219
220
Helper functions for time-related operations.
221
222
```typescript { .api }
223
/**
224
* Time utility functions for common time operations
225
*/
226
declare const time: {
227
/** Current timestamp in milliseconds */
228
now(): number;
229
/** Formats timestamp to readable string */
230
format(timestamp: number, format?: string): string;
231
/** Adds time interval to timestamp */
232
add(timestamp: number, interval: TimeInterval): number;
233
/** Subtracts time interval from timestamp */
234
subtract(timestamp: number, interval: TimeInterval): number;
235
};
236
237
interface TimeInterval {
238
years?: number;
239
months?: number;
240
days?: number;
241
hours?: number;
242
minutes?: number;
243
seconds?: number;
244
milliseconds?: number;
245
}
246
```
247
248
### Page Hash Utilities
249
250
Functions for working with URL hash and query parameters.
251
252
```typescript { .api }
253
/**
254
* Utilities for working with page hash
255
*/
256
declare const pageHash: {
257
/** Gets current page hash */
258
get(): string;
259
/** Sets page hash */
260
set(hash: string): void;
261
/** Observable for hash changes */
262
observable: Observable<string>;
263
};
264
265
/**
266
* Utilities for working with hash parameters
267
*/
268
declare const pageHashParams: {
269
/** Gets parameter from hash */
270
get(key: string): string | undefined;
271
/** Sets parameter in hash */
272
set(key: string, value: string): void;
273
/** Observable for hash parameter changes */
274
observable: Observable<Record<string, string>>;
275
};
276
```
277
278
### Fetch Utilities
279
280
Helper functions for HTTP requests and data fetching.
281
282
```typescript { .api }
283
/**
284
* Enhanced fetch utility with observable integration
285
* @param url - URL to fetch
286
* @param options - Fetch options
287
* @returns Promise resolving to response data
288
*/
289
declare const fetch: {
290
/** Standard fetch with observable integration */
291
<T>(url: string, options?: RequestInit): Promise<T>;
292
/** GET request helper */
293
get<T>(url: string, options?: RequestInit): Promise<T>;
294
/** POST request helper */
295
post<T>(url: string, data?: any, options?: RequestInit): Promise<T>;
296
/** PUT request helper */
297
put<T>(url: string, data?: any, options?: RequestInit): Promise<T>;
298
/** DELETE request helper */
299
delete<T>(url: string, options?: RequestInit): Promise<T>;
300
};
301
```
302
303
**Usage Examples:**
304
305
```typescript
306
import {
307
observable,
308
isObservable,
309
setAtPath,
310
computeSelector,
311
setSilently,
312
mergeIntoObservable
313
} from "@legendapp/state";
314
315
// Type checking
316
const user$ = observable({ name: "Alice", age: 30 });
317
console.log(isObservable(user$)); // true
318
console.log(isObservable("hello")); // false
319
320
// Path operations
321
const data = { user: { profile: { name: "" } } };
322
setAtPath(data, ["user", "profile", "name"], "Bob");
323
console.log(data.user.profile.name); // "Bob"
324
325
// Observable path operations
326
const state$ = observable({ user: { settings: { theme: "light" } } });
327
setInObservableAtPath(state$, ["user", "settings", "theme"], "dark");
328
329
// Silent updates (no change notifications)
330
const counter$ = observable(0);
331
counter$.onChange(() => console.log("Changed!"));
332
setSilently(counter$, 5); // No "Changed!" log
333
counter$.set(10); // Logs "Changed!"
334
335
// Merging objects into observables
336
const settings$ = observable({ theme: "light", language: "en" });
337
mergeIntoObservable(settings$,
338
{ theme: "dark" },
339
{ fontSize: 14, animation: true }
340
);
341
// settings$ now contains merged properties
342
343
// Selector computation
344
const name$ = observable("Alice");
345
const age$ = observable(30);
346
const greeting = computeSelector(() =>
347
`Hello, ${name$.get()}! You are ${age$.get()} years old.`
348
);
349
350
// Path construction/deconstruction
351
const baseObj = { app: { version: "1.0" } };
352
const newObj = constructObjectWithPath(baseObj, ["user", "profile"], { name: "Bob" });
353
// newObj = { app: { version: "1.0" }, user: { profile: { name: "Bob" } } }
354
355
const extracted = deconstructObjectWithPath(newObj, ["user", "profile", "name"]);
356
console.log(extracted); // "Bob"
357
358
// Type checking examples
359
console.log(isEmpty("")); // true
360
console.log(isEmpty([])); // true
361
console.log(isEmpty({})); // true
362
console.log(isEmpty(null)); // true
363
console.log(isEmpty("hello")); // false
364
365
console.log(isPrimitive("hello")); // true
366
console.log(isPrimitive(42)); // true
367
console.log(isPrimitive({})); // false
368
console.log(isPrimitive([])); // false
369
```