0
# Mathematical Operations
1
2
Immutable mathematical functions for basic arithmetic operations, designed to work well with functional programming patterns and signal-based reactive systems. These functions support both numeric and string operations where applicable.
3
4
## Capabilities
5
6
### Basic Arithmetic
7
8
Core mathematical operations for performing calculations without side effects.
9
10
```typescript { .api }
11
/**
12
* Addition: a + b + c + ...
13
* Supports both numbers and strings
14
*/
15
function add(...a: number[]): number;
16
function add(...a: string[]): string;
17
18
/**
19
* Subtraction: a - b - c - ...
20
* Note: Function name is misspelled in source code as "substract"
21
* @param a - Initial value
22
* @param b - Values to subtract
23
* @returns Result of subtraction
24
*/
25
function substract(a: number, ...b: number[]): number;
26
27
/**
28
* Multiplication: a * b * c * ...
29
* @param a - Initial value
30
* @param b - Values to multiply by
31
* @returns Result of multiplication
32
*/
33
function multiply(a: number, ...b: number[]): number;
34
35
/**
36
* Division: a / b / c / ...
37
* @param a - Initial value
38
* @param b - Values to divide by
39
* @returns Result of division
40
*/
41
function divide(a: number, ...b: number[]): number;
42
43
/**
44
* Exponentiation: a ** b ** c ** ...
45
* @param a - Base value
46
* @param b - Exponent values
47
* @returns Result of exponentiation
48
*/
49
function power(a: number, ...b: number[]): number;
50
```
51
52
**Usage Examples:**
53
54
```typescript
55
import { createSignal } from "solid-js";
56
import { add, substract, multiply, divide, power } from "@solid-primitives/utils/immutable";
57
58
// Basic arithmetic operations
59
const sum = add(1, 2, 3, 4); // 10
60
const stringConcat = add("Hello", " ", "World"); // "Hello World"
61
const difference = substract(100, 10, 5); // 85
62
const product = multiply(2, 3, 4); // 24
63
const quotient = divide(100, 2, 5); // 10
64
const exponent = power(2, 3, 2); // 2 ** 3 ** 2 = 512
65
66
// With reactive signals
67
const [values, setValues] = createSignal([1, 2, 3, 4, 5]);
68
const [multiplier, setMultiplier] = createSignal(2);
69
70
// Calculate sum reactively
71
const total = () => add(...values());
72
73
// Calculate scaled values
74
const scaled = () => multiply(total(), multiplier());
75
```
76
77
### Range and Constraint Operations
78
79
Functions for constraining values within specific ranges.
80
81
```typescript { .api }
82
/**
83
* Clamp a number value between two other values
84
* @param n - Number to clamp
85
* @param min - Minimum value
86
* @param max - Maximum value
87
* @returns Clamped value between min and max
88
*/
89
function clamp(n: number, min: number, max: number): number;
90
```
91
92
**Usage Examples:**
93
94
```typescript
95
import { clamp } from "@solid-primitives/utils/immutable";
96
import { createSignal } from "solid-js";
97
98
// Basic clamping
99
const clamped = clamp(15, 0, 10); // 10
100
const inRange = clamp(5, 0, 10); // 5
101
const tooLow = clamp(-5, 0, 10); // 0
102
103
// Reactive clamping for user input
104
const [userInput, setUserInput] = createSignal(0);
105
const [minValue] = createSignal(0);
106
const [maxValue] = createSignal(100);
107
108
const clampedValue = () => clamp(userInput(), minValue(), maxValue());
109
110
// Usage in component
111
setUserInput(150); // Input is 150
112
console.log(clampedValue()); // 100 (clamped to max)
113
```
114
115
### Complex Calculations
116
117
These functions can be combined for more complex mathematical operations:
118
119
**Usage Examples:**
120
121
```typescript
122
import { add, multiply, divide, clamp } from "@solid-primitives/utils/immutable";
123
import { createSignal } from "solid-js";
124
125
// Calculate weighted average with clamping
126
const calculateWeightedAverage = (values: number[], weights: number[]) => {
127
const weightedSum = values.reduce((sum, val, i) =>
128
add(sum, multiply(val, weights[i] || 1)), 0
129
);
130
const totalWeight = add(...weights);
131
const average = divide(weightedSum, totalWeight);
132
return clamp(average, 0, 100); // Clamp percentage to 0-100
133
};
134
135
// Reactive calculation example
136
const [scores, setScores] = createSignal([85, 92, 78, 95]);
137
const [weights, setWeights] = createSignal([0.2, 0.3, 0.25, 0.25]);
138
139
const finalGrade = () => calculateWeightedAverage(scores(), weights());
140
141
// Complex formula with signal updates
142
const [principal, setPrincipal] = createSignal(1000);
143
const [rate, setRate] = createSignal(0.05);
144
const [time, setTime] = createSignal(3);
145
146
// Compound interest calculation: A = P(1 + r)^t
147
const compoundInterest = () => {
148
const baseAmount = add(1, rate());
149
const finalAmount = multiply(principal(), power(baseAmount, time()));
150
return finalAmount;
151
};
152
```
153
154
### Signal Integration
155
156
These mathematical operations work seamlessly with Solid.js signals for reactive calculations:
157
158
**Usage Examples:**
159
160
```typescript
161
import { createSignal, createMemo } from "solid-js";
162
import { add, multiply, clamp } from "@solid-primitives/utils/immutable";
163
164
// Reactive shopping cart total
165
const [items, setItems] = createSignal([
166
{ price: 10.99, quantity: 2 },
167
{ price: 25.50, quantity: 1 },
168
{ price: 8.75, quantity: 3 }
169
]);
170
171
const subtotal = createMemo(() =>
172
items().reduce((total, item) =>
173
add(total, multiply(item.price, item.quantity)), 0
174
)
175
);
176
177
const [taxRate] = createSignal(0.08);
178
const tax = createMemo(() => multiply(subtotal(), taxRate()));
179
const total = createMemo(() => add(subtotal(), tax()));
180
181
// Reactive progress calculation with clamping
182
const [currentStep, setCurrentStep] = createSignal(0);
183
const [totalSteps] = createSignal(10);
184
185
const progress = createMemo(() =>
186
clamp(
187
multiply(divide(currentStep(), totalSteps()), 100),
188
0,
189
100
190
)
191
);
192
```
193
194
## Type Definitions
195
196
The mathematical operations maintain type safety while supporting multiple input types where appropriate:
197
198
```typescript { .api }
199
// add function supports both number and string arrays
200
function add(...a: number[]): number;
201
function add(...a: string[]): string;
202
203
// Other functions work with numbers
204
function substract(a: number, ...b: number[]): number; // Note: misspelled in source
205
function multiply(a: number, ...b: number[]): number;
206
function divide(a: number, ...b: number[]): number;
207
function power(a: number, ...b: number[]): number;
208
function clamp(n: number, min: number, max: number): number;
209
```
210
211
Note: The `add` function is overloaded to work with both numbers (performing addition) and strings (performing concatenation), making it versatile for different use cases in reactive applications.