0
# Generic Math Operations
1
2
Generic reactive wrapper that provides access to any Math method with full type safety and reactive behavior. This allows you to use any JavaScript Math function reactively without needing individual wrapper functions.
3
4
## Capabilities
5
6
### useMath
7
8
Generic function that creates reactive wrappers for any Math method by name, preserving full type safety and function signatures.
9
10
```typescript { .api }
11
/**
12
* Generic reactive wrapper for Math methods
13
* @param key - The name of the Math method to use
14
* @param args - Arguments to pass to the Math method (reactive)
15
* @returns Reactive result of the Math method call
16
*/
17
function useMath<K extends keyof Math>(
18
key: K,
19
...args: ArgumentsType<Reactified<Math[K], true>>
20
): ReturnType<Reactified<Math[K], true>>;
21
22
/**
23
* Type containing all Math method names that are callable functions
24
*/
25
type UseMathKeys = keyof {
26
[K in keyof Math as Math[K] extends (...args: any) => any ? K : never]: unknown
27
};
28
```
29
30
**Usage Examples:**
31
32
```typescript
33
import { ref, computed } from "vue";
34
import { useMath } from "@vueuse/math";
35
36
// Basic trigonometric functions
37
const angle = ref(Math.PI / 4); // 45 degrees
38
const sine = useMath('sin', angle);
39
const cosine = useMath('cos', angle);
40
const tangent = useMath('tan', angle);
41
42
console.log(sine.value); // ~0.707
43
console.log(cosine.value); // ~0.707
44
console.log(tangent.value); // ~1.000
45
46
// Power and logarithmic functions
47
const base = ref(2);
48
const exponent = ref(8);
49
const power = useMath('pow', base, exponent);
50
const log = useMath('log2', power);
51
52
console.log(power.value); // 256
53
console.log(log.value); // 8 (log2 of 256)
54
55
// Square root and other single-argument functions
56
const number = ref(16);
57
const sqrt = useMath('sqrt', number);
58
const cbrt = useMath('cbrt', number);
59
60
console.log(sqrt.value); // 4
61
console.log(cbrt.value); // ~2.52
62
63
// Min/Max with multiple arguments
64
const a = ref(5);
65
const b = ref(10);
66
const c = ref(3);
67
const min = useMath('min', a, b, c);
68
const max = useMath('max', a, b, c);
69
70
console.log(min.value); // 3
71
console.log(max.value); // 10
72
```
73
74
### Available Math Methods
75
76
All standard JavaScript Math methods are available through `useMath`:
77
78
```typescript { .api }
79
// Trigonometric functions
80
useMath('sin', angle);
81
useMath('cos', angle);
82
useMath('tan', angle);
83
useMath('asin', value);
84
useMath('acos', value);
85
useMath('atan', value);
86
useMath('atan2', y, x);
87
88
// Hyperbolic functions
89
useMath('sinh', value);
90
useMath('cosh', value);
91
useMath('tanh', value);
92
useMath('asinh', value);
93
useMath('acosh', value);
94
useMath('atanh', value);
95
96
// Exponential and logarithmic functions
97
useMath('exp', value);
98
useMath('expm1', value);
99
useMath('log', value);
100
useMath('log10', value);
101
useMath('log2', value);
102
useMath('log1p', value);
103
useMath('pow', base, exponent);
104
105
// Root functions
106
useMath('sqrt', value);
107
useMath('cbrt', value);
108
useMath('hypot', ...values);
109
110
// Rounding and integer functions
111
useMath('ceil', value);
112
useMath('floor', value);
113
useMath('round', value);
114
useMath('trunc', value);
115
useMath('sign', value);
116
117
// Min/Max and comparison
118
useMath('min', ...values);
119
useMath('max', ...values);
120
useMath('abs', value);
121
122
// Random (note: no arguments needed)
123
useMath('random'); // Always returns different ComputedRef
124
125
// Other mathematical functions
126
useMath('fround', value);
127
useMath('imul', a, b);
128
useMath('clz32', value);
129
```
130
131
## Advanced Usage Patterns
132
133
### Complex Mathematical Calculations
134
135
```typescript
136
import { ref, computed } from "vue";
137
import { useMath } from "@vueuse/math";
138
139
// Calculate distance between two points
140
const x1 = ref(0);
141
const y1 = ref(0);
142
const x2 = ref(3);
143
const y2 = ref(4);
144
145
// Using Pythagorean theorem: √((x2-x1)² + (y2-y1)²)
146
const deltaX = computed(() => x2.value - x1.value);
147
const deltaY = computed(() => y2.value - y1.value);
148
const deltaXSquared = useMath('pow', deltaX, 2);
149
const deltaYSquared = useMath('pow', deltaY, 2);
150
const sumOfSquares = computed(() => deltaXSquared.value + deltaYSquared.value);
151
const distance = useMath('sqrt', sumOfSquares);
152
153
console.log(distance.value); // 5
154
155
// Update coordinates - distance updates automatically
156
x2.value = 6;
157
y2.value = 8;
158
console.log(distance.value); // 10
159
```
160
161
### Animation Easing Functions
162
163
```typescript
164
import { ref, computed } from "vue";
165
import { useMath } from "@vueuse/math";
166
167
// Create easing functions using Math methods
168
const progress = ref(0); // 0 to 1
169
170
// Ease-in-sine
171
const easeInSine = computed(() => {
172
const halfPI = Math.PI / 2;
173
const progressAngle = computed(() => progress.value * halfPI);
174
const cos = useMath('cos', progressAngle);
175
return 1 - cos.value;
176
});
177
178
// Ease-out-expo
179
const easeOutExpo = computed(() => {
180
if (progress.value === 1) return 1;
181
const negativeProgress = computed(() => -10 * progress.value);
182
const pow = useMath('pow', 2, negativeProgress);
183
return 1 - pow.value;
184
});
185
186
// Animate through progress values
187
function animate() {
188
progress.value += 0.01;
189
190
console.log({
191
linear: progress.value,
192
easeInSine: easeInSine.value,
193
easeOutExpo: easeOutExpo.value
194
});
195
196
if (progress.value < 1) {
197
requestAnimationFrame(animate);
198
}
199
}
200
```
201
202
### Statistical Calculations
203
204
```typescript
205
import { ref, computed } from "vue";
206
import { useMath } from "@vueuse/math";
207
208
// Standard deviation calculation
209
const values = ref([2, 4, 4, 4, 5, 5, 7, 9]);
210
211
const mean = computed(() => {
212
return values.value.reduce((sum, val) => sum + val, 0) / values.value.length;
213
});
214
215
const variance = computed(() => {
216
const avg = mean.value;
217
const squaredDiffs = values.value.map(val => {
218
const diff = val - avg;
219
return diff * diff;
220
});
221
return squaredDiffs.reduce((sum, val) => sum + val, 0) / values.value.length;
222
});
223
224
const standardDeviation = useMath('sqrt', variance);
225
226
console.log({
227
mean: mean.value, // 5
228
variance: variance.value, // 4
229
stdDev: standardDeviation.value // 2
230
});
231
232
// Add new value - all statistics update automatically
233
values.value.push(10);
234
console.log({
235
mean: mean.value, // ~5.56
236
variance: variance.value, // ~5.58
237
stdDev: standardDeviation.value // ~2.36
238
});
239
```
240
241
### Physics Calculations
242
243
```typescript
244
import { ref, computed } from "vue";
245
import { useMath } from "@vueuse/math";
246
247
// Projectile motion calculator
248
const initialVelocity = ref(50); // m/s
249
const angle = ref(45); // degrees
250
const gravity = ref(9.81); // m/s²
251
252
// Convert angle to radians
253
const angleInRadians = computed(() => (angle.value * Math.PI) / 180);
254
const sinAngle = useMath('sin', angleInRadians);
255
const cosAngle = useMath('cos', angleInRadians);
256
257
// Calculate components
258
const vx = computed(() => initialVelocity.value * cosAngle.value);
259
const vy = computed(() => initialVelocity.value * sinAngle.value);
260
261
// Time of flight: t = 2 * vy / g
262
const timeOfFlight = computed(() => (2 * vy.value) / gravity.value);
263
264
// Maximum height: h = vy² / (2 * g)
265
const vySquared = useMath('pow', vy, 2);
266
const maxHeight = computed(() => vySquared.value / (2 * gravity.value));
267
268
// Range: R = vx * t
269
const range = computed(() => vx.value * timeOfFlight.value);
270
271
console.log({
272
timeOfFlight: timeOfFlight.value, // ~7.21 seconds
273
maxHeight: maxHeight.value, // ~63.78 meters
274
range: range.value // ~254.96 meters
275
});
276
277
// Change launch angle to optimize range
278
angle.value = 30;
279
console.log(`Range at 30°: ${range.value.toFixed(2)}m`);
280
281
angle.value = 45;
282
console.log(`Range at 45°: ${range.value.toFixed(2)}m`); // Optimal angle
283
```