npm-lodash

Description
Comprehensive JavaScript utility library with 300+ methods for arrays, objects, strings, functions, and more.
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/npm-lodash@4.5.0

math-number-methods.md docs/

1
# Math & Number Methods
2
3
Mathematical utilities for arithmetic, aggregation, and numerical processing. These methods provide essential mathematical operations and number manipulation functions.
4
5
## Capabilities
6
7
### Basic Arithmetic
8
9
#### Core Math Operations
10
Perform basic mathematical operations with proper handling of edge cases.
11
12
```javascript { .api }
13
/**
14
* Adds two numbers
15
* @param augend - The first number in an addition
16
* @param addend - The second number in an addition
17
* @returns Returns the sum
18
*/
19
function add(augend, addend);
20
21
/**
22
* Subtracts two numbers
23
* @param minuend - The first number in a subtraction
24
* @param subtrahend - The second number in a subtraction
25
* @returns Returns the difference
26
*/
27
function subtract(minuend, subtrahend);
28
29
/**
30
* Multiplies two numbers
31
* @param multiplier - The first number in a multiplication
32
* @param multiplicand - The second number in a multiplication
33
* @returns Returns the product
34
*/
35
function multiply(multiplier, multiplicand);
36
37
/**
38
* Divides two numbers
39
* @param dividend - The first number in a division
40
* @param divisor - The second number in a division
41
* @returns Returns the quotient
42
*/
43
function divide(dividend, divisor);
44
```
45
46
### Rounding & Precision
47
48
#### Rounding Functions
49
Round numbers to specified precision.
50
51
```javascript { .api }
52
/**
53
* Computes number rounded up to precision
54
* @param number - The number to round up
55
* @param precision - The precision to round up to
56
* @returns Returns the rounded up number
57
*/
58
function ceil(number, precision = 0);
59
60
/**
61
* Computes number rounded down to precision
62
* @param number - The number to round down
63
* @param precision - The precision to round down to
64
* @returns Returns the rounded down number
65
*/
66
function floor(number, precision = 0);
67
68
/**
69
* Computes number rounded to precision
70
* @param number - The number to round
71
* @param precision - The precision to round to
72
* @returns Returns the rounded number
73
*/
74
function round(number, precision = 0);
75
```
76
77
### Array Aggregation
78
79
#### Min & Max
80
Find minimum and maximum values in arrays.
81
82
```javascript { .api }
83
/**
84
* Computes the maximum value of array
85
* @param array - The array to iterate over
86
* @returns Returns the maximum value
87
*/
88
function max(array);
89
90
/**
91
* Like max except that it accepts iteratee which is invoked for each element in array to generate the criterion by which the value is ranked
92
* @param array - The array to iterate over
93
* @param iteratee - The iteratee invoked per element
94
* @returns Returns the maximum value
95
*/
96
function maxBy(array, iteratee);
97
98
/**
99
* Computes the minimum value of array
100
* @param array - The array to iterate over
101
* @returns Returns the minimum value
102
*/
103
function min(array);
104
105
/**
106
* Like min except that it accepts iteratee which is invoked for each element in array to generate the criterion by which the value is ranked
107
* @param array - The array to iterate over
108
* @param iteratee - The iteratee invoked per element
109
* @returns Returns the minimum value
110
*/
111
function minBy(array, iteratee);
112
```
113
114
#### Sum & Mean
115
Calculate totals and averages.
116
117
```javascript { .api }
118
/**
119
* Computes the sum of the values in array
120
* @param array - The array to iterate over
121
* @returns Returns the sum
122
*/
123
function sum(array);
124
125
/**
126
* Like sum except that it accepts iteratee which is invoked for each element in array to generate the value to be summed
127
* @param array - The array to iterate over
128
* @param iteratee - The iteratee invoked per element
129
* @returns Returns the sum
130
*/
131
function sumBy(array, iteratee);
132
133
/**
134
* Computes the mean of the values in array
135
* @param array - The array to iterate over
136
* @returns Returns the mean
137
*/
138
function mean(array);
139
140
/**
141
* Like mean except that it accepts iteratee which is invoked for each element in array to generate the value to be averaged
142
* @param array - The array to iterate over
143
* @param iteratee - The iteratee invoked per element
144
* @returns Returns the mean
145
*/
146
function meanBy(array, iteratee);
147
```
148
149
### Number Utilities
150
151
#### Range Operations
152
Constrain and test number ranges.
153
154
```javascript { .api }
155
/**
156
* Clamps number within the inclusive lower and upper bounds
157
* @param number - The number to clamp
158
* @param lower - The lower bound
159
* @param upper - The upper bound
160
* @returns Returns the clamped number
161
*/
162
function clamp(number, lower, upper);
163
164
/**
165
* Checks if number is between start and up to, but not including, end
166
* @param number - The number to check
167
* @param start - The start of the range
168
* @param end - The end of the range
169
* @returns Returns true if number is in the range, else false
170
*/
171
function inRange(number, start = 0, end);
172
```
173
174
#### Random Number Generation
175
Generate random numbers within specified ranges.
176
177
```javascript { .api }
178
/**
179
* Produces a random number between the inclusive lower and upper bounds
180
* @param lower - The lower bound
181
* @param upper - The upper bound
182
* @param floating - Specify returning a floating-point number
183
* @returns Returns the random number
184
*/
185
function random(lower = 0, upper = 1, floating);
186
```
187
188
## Usage Examples
189
190
```javascript
191
import {
192
add, subtract, multiply, divide,
193
ceil, floor, round,
194
max, min, sum, mean,
195
clamp, inRange, random
196
} from "lodash";
197
198
// Basic arithmetic
199
console.log(add(6, 4)); // 10
200
console.log(subtract(6, 4)); // 2
201
console.log(multiply(6, 4)); // 24
202
console.log(divide(6, 4)); // 1.5
203
204
// Precision rounding
205
console.log(ceil(4.006)); // 5
206
console.log(ceil(6.004, 2)); // 6.01
207
console.log(ceil(6040, -2)); // 6100
208
209
console.log(floor(4.006)); // 4
210
console.log(floor(0.046, 2)); // 0.04
211
console.log(floor(4060, -2)); // 4000
212
213
console.log(round(4.006)); // 4
214
console.log(round(4.006, 2)); // 4.01
215
console.log(round(4060, -2)); // 4100
216
217
// Array aggregation
218
const numbers = [4, 2, 8, 6];
219
console.log(max(numbers)); // 8
220
console.log(min(numbers)); // 2
221
console.log(sum(numbers)); // 20
222
console.log(mean(numbers)); // 5
223
224
// Working with objects
225
const users = [
226
{ name: 'John', age: 30, score: 85 },
227
{ name: 'Jane', age: 25, score: 92 },
228
{ name: 'Bob', age: 35, score: 78 }
229
];
230
231
console.log(maxBy(users, 'age')); // { name: 'Bob', age: 35, score: 78 }
232
console.log(minBy(users, 'score')); // { name: 'Bob', age: 35, score: 78 }
233
console.log(sumBy(users, 'score')); // 255
234
console.log(meanBy(users, 'age')); // 30
235
236
// Number range operations
237
console.log(clamp(10, 5, 15)); // 10 (within range)
238
console.log(clamp(3, 5, 15)); // 5 (clamped to lower)
239
console.log(clamp(20, 5, 15)); // 15 (clamped to upper)
240
241
console.log(inRange(3, 2, 4)); // true
242
console.log(inRange(4, 8)); // true (0 to 8)
243
console.log(inRange(4, 2)); // false
244
console.log(inRange(2, 2)); // false
245
console.log(inRange(-3, -2, -6)); // true
246
247
// Random number generation
248
console.log(random(0, 5)); // Random integer between 0-5
249
console.log(random(5)); // Random integer between 0-5
250
console.log(random(1.2, 5.2)); // Random float between 1.2-5.2
251
console.log(random(0, 1, true)); // Random float between 0-1
252
253
// Practical examples
254
255
// Calculate statistics for test scores
256
const testScores = [85, 92, 78, 96, 88, 91, 84];
257
258
const stats = {
259
count: testScores.length,
260
sum: sum(testScores),
261
average: mean(testScores),
262
highest: max(testScores),
263
lowest: min(testScores),
264
range: max(testScores) - min(testScores)
265
};
266
267
console.log(stats);
268
// {
269
// count: 7,
270
// sum: 614,
271
// average: 87.71428571428571,
272
// highest: 96,
273
// lowest: 78,
274
// range: 18
275
// }
276
277
// Financial calculations with proper rounding
278
const prices = [19.99, 25.50, 12.75, 8.25];
279
const taxRate = 0.08;
280
281
const subtotal = sum(prices);
282
const tax = round(multiply(subtotal, taxRate), 2);
283
const total = round(add(subtotal, tax), 2);
284
285
console.log(`Subtotal: $${subtotal.toFixed(2)}`);
286
console.log(`Tax: $${tax.toFixed(2)}`);
287
console.log(`Total: $${total.toFixed(2)}`);
288
289
// Progress bar calculation
290
function calculateProgress(current, total) {
291
const percentage = divide(current, total) * 100;
292
return clamp(round(percentage, 1), 0, 100);
293
}
294
295
console.log(calculateProgress(250, 1000)); // 25.0
296
console.log(calculateProgress(1200, 1000)); // 100.0 (clamped)
297
298
// Random sampling utility
299
function sampleNumbers(count, min, max, floating = false) {
300
return Array.from({ length: count }, () =>
301
random(min, max, floating)
302
);
303
}
304
305
console.log(sampleNumbers(5, 1, 10)); // [3, 7, 1, 9, 5]
306
console.log(sampleNumbers(3, 0, 1, true)); // [0.234, 0.876, 0.123]
307
308
// Grade calculation system
309
function calculateGrade(scores, weights) {
310
if (scores.length !== weights.length) {
311
throw new Error('Scores and weights must have same length');
312
}
313
314
const weightedScores = scores.map((score, index) =>
315
multiply(score, weights[index])
316
);
317
318
const totalWeightedScore = sum(weightedScores);
319
const totalWeight = sum(weights);
320
321
return round(divide(totalWeightedScore, totalWeight), 2);
322
}
323
324
const examScores = [85, 92, 88];
325
const examWeights = [0.3, 0.4, 0.3]; // 30%, 40%, 30%
326
327
console.log(calculateGrade(examScores, examWeights)); // 88.5
328
329
// Budget allocation with constraints
330
function allocateBudget(totalBudget, categories) {
331
const totalRequested = sumBy(categories, 'requested');
332
333
if (totalRequested <= totalBudget) {
334
// If under budget, allocate as requested
335
return categories.map(cat => ({
336
...cat,
337
allocated: cat.requested
338
}));
339
}
340
341
// If over budget, proportionally reduce
342
const ratio = divide(totalBudget, totalRequested);
343
344
return categories.map(cat => ({
345
...cat,
346
allocated: round(multiply(cat.requested, ratio), 2)
347
}));
348
}
349
350
const budget = 10000;
351
const categories = [
352
{ name: 'Marketing', requested: 4000, minimum: 2000 },
353
{ name: 'Development', requested: 5000, minimum: 3000 },
354
{ name: 'Operations', requested: 3000, minimum: 1500 }
355
];
356
357
console.log(allocateBudget(budget, categories));
358
359
// Statistical analysis helper
360
function analyzeDataset(values) {
361
if (!values || values.length === 0) {
362
return null;
363
}
364
365
const sorted = [...values].sort((a, b) => a - b);
366
const length = values.length;
367
368
return {
369
count: length,
370
sum: sum(values),
371
mean: mean(values),
372
median: length % 2 === 0
373
? mean([sorted[length / 2 - 1], sorted[length / 2]])
374
: sorted[Math.floor(length / 2)],
375
min: min(values),
376
max: max(values),
377
range: max(values) - min(values)
378
};
379
}
380
381
const dataset = [12, 15, 18, 22, 25, 28, 30, 35, 38, 42];
382
console.log(analyzeDataset(dataset));
383
```