0
# Environment and Utilities
1
2
Environment detection, utility functions, and general-purpose helpers for common programming tasks. These utilities provide runtime environment information and common programming patterns that work well with Solid.js applications.
3
4
## Capabilities
5
6
### Environment Detection
7
8
Constants and functions for detecting the runtime environment.
9
10
```typescript { .api }
11
/**
12
* True when running on the server (from solid-js/web)
13
*/
14
const isServer: boolean;
15
16
/**
17
* True when running on the client (!isServer)
18
*/
19
const isClient: boolean;
20
21
/**
22
* True when in development mode on the client
23
*/
24
const isDev: boolean;
25
26
/**
27
* True when in production mode (!isDev)
28
*/
29
const isProd: boolean;
30
```
31
32
**Usage Examples:**
33
34
```typescript
35
import { isServer, isClient, isDev, isProd } from "@solid-primitives/utils";
36
37
// Conditional logic based on environment
38
if (isServer) {
39
console.log("Running on server");
40
} else {
41
console.log("Running on client");
42
}
43
44
// Development-only code
45
if (isDev) {
46
console.log("Debug information");
47
}
48
49
// Client-side only operations
50
if (isClient) {
51
localStorage.setItem("key", "value");
52
}
53
54
// Production optimizations
55
if (isProd) {
56
// Enable analytics, disable debug logs, etc.
57
}
58
```
59
60
### Utility Functions
61
62
Common utility functions for everyday programming tasks.
63
64
```typescript { .api }
65
/**
66
* No operation function
67
*/
68
function noop(...a: any[]): void;
69
70
/**
71
* Function that always returns true
72
*/
73
function trueFn(): boolean;
74
75
/**
76
* Function that always returns false
77
*/
78
function falseFn(): boolean;
79
80
/**
81
* @deprecated use equalFn from "solid-js"
82
*/
83
const defaultEquals: typeof equalFn;
84
```
85
86
**Usage Examples:**
87
88
```typescript
89
import { noop, trueFn, falseFn } from "@solid-primitives/utils";
90
91
// Default callback that does nothing
92
const handleClick = someCondition ? actualHandler : noop;
93
94
// Default predicates
95
const alwaysInclude = trueFn;
96
const alwaysExclude = falseFn;
97
98
// Filter arrays with utility functions
99
const items = [1, 2, 3, 4, 5];
100
const allItems = items.filter(trueFn); // [1, 2, 3, 4, 5]
101
const noItems = items.filter(falseFn); // []
102
```
103
104
### Signal Options
105
106
Pre-configured signal options for common patterns.
107
108
```typescript { .api }
109
/**
110
* SignalOptions with equals: false
111
*/
112
const EQUALS_FALSE_OPTIONS: SignalOptions<unknown>;
113
114
/**
115
* SignalOptions with internal: true
116
*/
117
const INTERNAL_OPTIONS: SignalOptions<unknown>;
118
```
119
120
**Usage Examples:**
121
122
```typescript
123
import { createSignal } from "solid-js";
124
import { EQUALS_FALSE_OPTIONS, INTERNAL_OPTIONS } from "@solid-primitives/utils";
125
126
// Signal that always updates (bypasses equality check)
127
const [counter, setCounter] = createSignal(0, EQUALS_FALSE_OPTIONS);
128
129
// Internal signal (won't trigger dev warnings)
130
const [internalState, setInternalState] = createSignal(null, INTERNAL_OPTIONS);
131
```
132
133
### Type Checking and Validation
134
135
Functions for runtime type checking and validation.
136
137
```typescript { .api }
138
/**
139
* Check if the value is an instance of a class
140
* @param v - Value to check
141
* @param c - Class constructor to check against
142
* @returns True if value is instance of class
143
*/
144
function ofClass(v: any, c: AnyClass): boolean;
145
146
/**
147
* Check if value is typeof "object" or "function"
148
* @param value - Value to check
149
* @returns True if value is an object
150
*/
151
function isObject(value: any): value is AnyObject;
152
153
/**
154
* Type guard for non-nullable values
155
* @param i - Value to check
156
* @returns True if value is not null or undefined
157
*/
158
function isNonNullable<T>(i: T): i is NonNullable<T>;
159
160
/**
161
* Filter array removing null and undefined values
162
* @param arr - Array to filter
163
* @returns New array with non-nullable values only
164
*/
165
function filterNonNullable<T extends readonly unknown[]>(arr: T): NonNullable<T[number]>[];
166
```
167
168
**Usage Examples:**
169
170
```typescript
171
import { ofClass, isObject, isNonNullable, filterNonNullable } from "@solid-primitives/utils";
172
173
// Class instance checking
174
class User {}
175
const user = new User();
176
console.log(ofClass(user, User)); // true
177
console.log(ofClass({}, User)); // false
178
179
// Object type checking
180
console.log(isObject({})); // true
181
console.log(isObject(null)); // false
182
console.log(isObject("string")); // false
183
184
// Null checking and filtering
185
const mixedArray = [1, null, "hello", undefined, {}, 0];
186
const nonNullable = filterNonNullable(mixedArray); // [1, "hello", {}, 0]
187
188
// Type guard usage
189
const value: string | null = getValue();
190
if (isNonNullable(value)) {
191
// value is definitely string here
192
console.log(value.toUpperCase());
193
}
194
```
195
196
### Array and Comparison Utilities
197
198
General-purpose utilities for working with arrays and comparing values.
199
200
```typescript { .api }
201
/**
202
* Compare two values (-1, 0, 1)
203
* @param a - First value
204
* @param b - Second value
205
* @returns -1 if a < b, 1 if a > b, 0 if equal
206
*/
207
function compare(a: any, b: any): number;
208
209
/**
210
* Check shallow array equality
211
* @param a - First array
212
* @param b - Second array
213
* @returns True if arrays are shallow equal
214
*/
215
function arrayEquals(a: readonly unknown[], b: readonly unknown[]): boolean;
216
217
/**
218
* Convert value to array if not already array
219
* @param value - Value to convert
220
* @returns Array containing the value(s)
221
*/
222
function asArray<T>(value: T): (T extends any[] ? T[number] : NonNullable<T>)[];
223
```
224
225
**Usage Examples:**
226
227
```typescript
228
import { compare, arrayEquals, asArray } from "@solid-primitives/utils";
229
230
// Comparison function for sorting
231
const numbers = [3, 1, 4, 1, 5];
232
numbers.sort(compare); // [1, 1, 3, 4, 5]
233
234
// Array equality checking
235
const arr1 = [1, 2, 3];
236
const arr2 = [1, 2, 3];
237
const arr3 = [1, 2, 4];
238
console.log(arrayEquals(arr1, arr2)); // true
239
console.log(arrayEquals(arr1, arr3)); // false
240
241
// Convert to array
242
console.log(asArray("single")); // ["single"]
243
console.log(asArray([1, 2, 3])); // [1, 2, 3]
244
console.log(asArray(null)); // []
245
```
246
247
### Function Utilities
248
249
Utilities for working with and combining functions.
250
251
```typescript { .api }
252
/**
253
* Returns a function that will call all functions in the order they were chained
254
* @param callbacks - Iterable of callback functions
255
* @returns Combined function
256
*/
257
function chain<Args extends [] | any[]>(callbacks: {
258
[Symbol.iterator](): IterableIterator<((...args: Args) => any) | undefined>;
259
}): (...args: Args) => void;
260
261
/**
262
* Returns a function that will call all functions in reversed order
263
* @param callbacks - Array of callback functions
264
* @returns Combined function
265
*/
266
function reverseChain<Args extends [] | any[]>(
267
callbacks: (((...args: Args) => any) | undefined)[]
268
): (...args: Args) => void;
269
```
270
271
**Usage Examples:**
272
273
```typescript
274
import { chain, reverseChain } from "@solid-primitives/utils";
275
276
// Chain multiple callbacks
277
const callbacks = [
278
(msg: string) => console.log("First:", msg),
279
(msg: string) => console.log("Second:", msg),
280
(msg: string) => console.log("Third:", msg)
281
];
282
283
const chained = chain(callbacks);
284
chained("Hello"); // Logs: "First: Hello", "Second: Hello", "Third: Hello"
285
286
const reversed = reverseChain(callbacks);
287
reversed("World"); // Logs: "Third: World", "Second: World", "First: World"
288
289
// With undefined callbacks (safely handled)
290
const mixedCallbacks = [
291
(msg: string) => console.log("Valid:", msg),
292
undefined,
293
(msg: string) => console.log("Also valid:", msg)
294
];
295
296
const safeMixed = chain(mixedCallbacks);
297
safeMixed("Test"); // Only valid callbacks are called
298
```
299
300
### Object Utilities
301
302
Enhanced object utility functions with better type safety.
303
304
```typescript { .api }
305
/**
306
* Get entries of an object with better typing
307
*/
308
const entries: <T extends object>(obj: T) => [keyof T, T[keyof T]][];
309
310
/**
311
* Get keys of an object with better typing
312
*/
313
const keys: <T extends object>(object: T) => (keyof T)[];
314
```
315
316
**Usage Examples:**
317
318
```typescript
319
import { entries, keys } from "@solid-primitives/utils";
320
321
const user = {
322
id: 1,
323
name: "Alice",
324
email: "alice@example.com"
325
};
326
327
// Typed object iteration
328
const userEntries = entries(user); // [["id", 1], ["name", "Alice"], ["email", "alice@example.com"]]
329
const userKeys = keys(user); // ["id", "name", "email"]
330
331
// Use in reactive contexts
332
import { createSignal, createMemo } from "solid-js";
333
334
const [userState, setUserState] = createSignal(user);
335
const userProperties = createMemo(() => keys(userState()));
336
const userValues = createMemo(() => entries(userState()).map(([, value]) => value));
337
```
338
339
## Types
340
341
```typescript { .api }
342
type AnyObject = Record<PropertyKey, any>;
343
type AnyClass = abstract new (...args: any) => any;
344
type Noop = (...a: any[]) => void;
345
```