0
# Number Module
1
2
Sugar's Number module provides comprehensive functionality for number operations, formatting, mathematical calculations, and date creation from numeric values. It extends JavaScript's native Number object with over 50 methods for practical number manipulation and mathematical operations.
3
4
## Core Imports
5
6
```javascript
7
import Sugar from 'sugar';
8
9
// Access Number methods via Sugar.Number
10
Sugar.Number.random(1, 100);
11
Sugar.Number.format(12345.67, 2);
12
13
// Or extend native numbers for instance methods
14
Sugar.extend();
15
(42).times(i => console.log(i));
16
(1000).bytes();
17
```
18
19
For CommonJS:
20
21
```javascript
22
const Sugar = require('sugar');
23
Sugar.extend();
24
```
25
26
## Capabilities
27
28
### Number Creation
29
30
Generate random numbers and create number ranges.
31
32
```javascript { .api }
33
/**
34
* Generate a random number between two values (inclusive)
35
* @param n1 - First number (default: 0)
36
* @param n2 - Second number (default: 1)
37
* @returns Random number in the specified range
38
*/
39
function random(n1?: number, n2?: number): number;
40
41
/**
42
* Create an array representing a range of numbers
43
* @param start - Starting number (default: 0)
44
* @param end - Ending number (default: 0)
45
* @returns Array of numbers in the range
46
*/
47
function range(start?: number, end?: number): number[];
48
```
49
50
**Usage Examples:**
51
52
```javascript
53
// Random numbers
54
Sugar.Number.random(); // 0.0 to 1.0
55
Sugar.Number.random(1, 6); // 1 to 6 (dice roll)
56
Sugar.Number.random(100); // 0 to 100
57
58
// Number ranges
59
Sugar.Number.range(1, 5); // [1, 2, 3, 4, 5]
60
Sugar.Number.range(-2, 2); // [-2, -1, 0, 1, 2]
61
62
// With native extension
63
Math.random.call(null, 1, 10); // Using Sugar's enhanced random
64
```
65
66
### Number Formatting
67
68
Format numbers for display in various formats including abbreviated, byte sizes, durations, and more.
69
70
```javascript { .api }
71
/**
72
* Format number with abbreviated suffixes (K, M, B, etc.)
73
* @param instance - Number to format
74
* @param precision - Decimal places (default: 0)
75
* @returns Abbreviated string representation
76
*/
77
function abbr(instance: number, precision?: number): string;
78
79
/**
80
* Format number as byte size with appropriate units
81
* @param instance - Number to format as bytes
82
* @param precision - Decimal places (default: 0)
83
* @param binary - Use binary (1024) vs decimal (1000) base (default: false)
84
* @param units - Unit system to use (default: "bytes")
85
* @returns Formatted byte string
86
*/
87
function bytes(instance: number, precision?: number, binary?: boolean, units?: string): string;
88
89
/**
90
* Format number as duration string
91
* @param instance - Number of milliseconds
92
* @param locale - Locale for formatting (default: current locale)
93
* @returns Human-readable duration string
94
*/
95
function duration(instance: number, locale?: string): string;
96
97
/**
98
* Format number with thousands separators
99
* @param instance - Number to format
100
* @param place - Decimal places (default: 0)
101
* @returns Formatted number string
102
*/
103
function format(instance: number, place?: number): string;
104
105
/**
106
* Format number as hexadecimal string
107
* @param instance - Number to convert
108
* @param pad - Minimum width with zero padding (default: 1)
109
* @returns Hexadecimal string representation
110
*/
111
function hex(instance: number, pad?: number): string;
112
113
/**
114
* Format number with metric unit suffixes
115
* @param instance - Number to format
116
* @param precision - Decimal places (default: 0)
117
* @param units - Unit system to use (default: "")
118
* @returns Formatted metric string
119
*/
120
function metric(instance: number, precision?: number, units?: string): string;
121
122
/**
123
* Format number as ordinal (1st, 2nd, 3rd, etc.)
124
* @param instance - Number to ordinalize
125
* @returns Ordinal string representation
126
*/
127
function ordinalize(instance: number): string;
128
129
/**
130
* Pad number with leading zeros or other characters
131
* @param instance - Number to pad
132
* @param place - Minimum width (default: 1)
133
* @param sign - Include sign for positive numbers (default: false)
134
* @param base - Number base for conversion (default: 10)
135
* @returns Padded string representation
136
*/
137
function pad(instance: number, place?: number, sign?: boolean, base?: number): string;
138
```
139
140
**Usage Examples:**
141
142
```javascript
143
// Abbreviation formatting
144
(1000).abbr(); // "1K"
145
(1500000).abbr(1); // "1.5M"
146
(2300000000).abbr(); // "2B"
147
148
// Byte formatting
149
(1024).bytes(); // "1KB"
150
(1536).bytes(1, true); // "1.5KB" (binary)
151
(1000).bytes(0, false); // "1KB" (decimal)
152
153
// Duration formatting
154
(5000).duration(); // "5 seconds"
155
(3661000).duration(); // "1 hour"
156
(90000).duration(); // "1 minute"
157
158
// Number formatting
159
(1234567.89).format(2); // "1,234,567.89"
160
(1000).format(); // "1,000"
161
162
// Hexadecimal formatting
163
(255).hex(); // "ff"
164
(10).hex(4); // "000a"
165
166
// Metric formatting
167
(1000).metric(); // "1k"
168
(1500000).metric(1, "g"); // "1.5Mg"
169
170
// Ordinal formatting
171
(1).ordinalize(); // "1st"
172
(22).ordinalize(); // "22nd"
173
(103).ordinalize(); // "103rd"
174
175
// Padding
176
(5).pad(3); // "005"
177
(-5).pad(4, true); // "-005"
178
(10).pad(4, false, 2); // "1010" (binary)
179
```
180
181
### Mathematical Operations
182
183
Extended mathematical functions beyond the standard Math object, with precision control for rounding.
184
185
```javascript { .api }
186
/**
187
* Mathematical functions - trigonometric, logarithmic, and basic math
188
*/
189
function abs(instance: number): number;
190
function acos(instance: number): number;
191
function asin(instance: number): number;
192
function atan(instance: number): number;
193
function cos(instance: number): number;
194
function exp(instance: number): number;
195
function log(instance: number): number;
196
function pow(instance: number, power: number): number;
197
function sin(instance: number): number;
198
function sqrt(instance: number): number;
199
function tan(instance: number): number;
200
201
/**
202
* Rounding functions with optional precision
203
* @param instance - Number to round
204
* @param precision - Decimal places for precision (default: 0)
205
* @returns Rounded number
206
*/
207
function ceil(instance: number, precision?: number): number;
208
function floor(instance: number, precision?: number): number;
209
function round(instance: number, precision?: number): number;
210
211
/**
212
* Limit number to maximum value
213
* @param instance - Number to cap
214
* @param max - Maximum value (default: instance)
215
* @returns Number capped at maximum
216
*/
217
function cap(instance: number, max?: number): number;
218
219
/**
220
* Constrain number to range between two values
221
* @param instance - Number to clamp
222
* @param start - Minimum value (default: instance)
223
* @param end - Maximum value (default: instance)
224
* @returns Number constrained to range
225
*/
226
function clamp(instance: number, start?: number, end?: number): number;
227
228
/**
229
* Convert number to character using String.fromCharCode
230
* @param instance - Character code number
231
* @returns Character string
232
*/
233
function chr(instance: number): string;
234
235
/**
236
* Ensure value is a number type
237
* @param instance - Value to convert
238
* @returns Number representation
239
*/
240
function toNumber(instance: number): number;
241
```
242
243
**Usage Examples:**
244
245
```javascript
246
// Basic math functions
247
(-5).abs(); // 5
248
(0.5).acos(); // 1.0471975511965979
249
(1).asin(); // 1.5707963267948966
250
(Math.PI/4).cos(); // 0.7071067811865476
251
(2).log(); // 0.6931471805599453
252
(2).pow(3); // 8
253
(9).sqrt(); // 3
254
255
// Precision rounding
256
(4.6789).ceil(2); // 4.68
257
(4.6789).floor(2); // 4.67
258
(4.6789).round(2); // 4.68
259
(4.6234).round(1); // 4.6
260
261
// Range limiting
262
(150).cap(100); // 100
263
(50).cap(100); // 50
264
(150).clamp(25, 100); // 100
265
(-10).clamp(0, 50); // 0
266
(25).clamp(10, 30); // 25
267
268
// Character conversion
269
(65).chr(); // "A"
270
(97).chr(); // "a"
271
(8364).chr(); // "€"
272
273
// Type conversion
274
(42.7).toNumber(); // 42.7
275
```
276
277
### Number Tests
278
279
Test number properties like parity, type, and mathematical relationships.
280
281
```javascript { .api }
282
/**
283
* Test if number is even
284
* @param instance - Number to test
285
* @returns True if even, false if odd
286
*/
287
function isEven(instance: number): boolean;
288
289
/**
290
* Test if number is odd
291
* @param instance - Number to test
292
* @returns True if odd, false if even
293
*/
294
function isOdd(instance: number): boolean;
295
296
/**
297
* Test if number is an integer
298
* @param instance - Number to test
299
* @returns True if integer, false if decimal
300
*/
301
function isInteger(instance: number): boolean;
302
303
/**
304
* Test if number is a multiple of another number
305
* @param instance - Number to test
306
* @param num - Number to check as multiple
307
* @returns True if instance is multiple of num
308
*/
309
function isMultipleOf(instance: number, num: number): boolean;
310
```
311
312
**Usage Examples:**
313
314
```javascript
315
// Parity tests
316
(4).isEven(); // true
317
(4).isOdd(); // false
318
(7).isEven(); // false
319
(7).isOdd(); // true
320
321
// Integer test
322
(42).isInteger(); // true
323
(42.5).isInteger(); // false
324
(0).isInteger(); // true
325
326
// Multiple test
327
(15).isMultipleOf(3); // true
328
(15).isMultipleOf(4); // false
329
(0).isMultipleOf(5); // true
330
(8).isMultipleOf(2); // true
331
```
332
333
### Number Iteration
334
335
Execute functions multiple times or iterate through number ranges.
336
337
```javascript { .api }
338
/**
339
* Execute function n times, collecting results
340
* @param instance - Number of times to execute
341
* @param indexMapFn - Function to execute on each iteration
342
* @returns Array of results from function calls
343
*/
344
function times<T>(instance: number, indexMapFn?: (i: number) => T): T[];
345
346
/**
347
* Count from instance up to target number
348
* @param instance - Starting number
349
* @param num - Target number
350
* @param step - Step size (default: 1)
351
* @param everyFn - Function to execute for each step
352
* @returns Array of results
353
*/
354
function upto<T>(instance: number, num: number, step?: number, everyFn?: (i: number) => T): T[];
355
356
/**
357
* Count from instance down to target number
358
* @param instance - Starting number
359
* @param num - Target number
360
* @param step - Step size (default: 1)
361
* @param everyFn - Function to execute for each step
362
* @returns Array of results
363
*/
364
function downto<T>(instance: number, num: number, step?: number, everyFn?: (i: number) => T): T[];
365
```
366
367
**Usage Examples:**
368
369
```javascript
370
// Execute function multiple times
371
(3).times(i => console.log(i)); // Logs: 0, 1, 2
372
(5).times(i => i * 2); // Returns: [0, 2, 4, 6, 8]
373
(4).times(); // Returns: [0, 1, 2, 3]
374
375
// Count up with function
376
(1).upto(5, 1, i => i * i); // [1, 4, 9, 16, 25]
377
(0).upto(10, 2, i => i); // [0, 2, 4, 6, 8, 10]
378
379
// Count down with function
380
(5).downto(1, 1, i => `Item ${i}`); // ["Item 5", "Item 4", "Item 3", "Item 2", "Item 1"]
381
(10).downto(0, 3, i => i); // [10, 7, 4, 1]
382
```
383
384
### Date Creation Methods
385
386
Create Date objects using numbers as time duration values.
387
388
```javascript { .api }
389
/**
390
* Duration conversion methods - convert number to milliseconds
391
*/
392
function day(instance: number): number;
393
function days(instance: number): number;
394
function hour(instance: number): number;
395
function hours(instance: number): number;
396
function minute(instance: number): number;
397
function minutes(instance: number): number;
398
function second(instance: number): number;
399
function seconds(instance: number): number;
400
function week(instance: number): number;
401
function weeks(instance: number): number;
402
function month(instance: number): number;
403
function months(instance: number): number;
404
function year(instance: number): number;
405
function years(instance: number): number;
406
407
/**
408
* Create dates relative to now (past)
409
*/
410
function dayAgo(instance: number): Date;
411
function daysAgo(instance: number): Date;
412
function hourAgo(instance: number): Date;
413
function hoursAgo(instance: number): Date;
414
function minuteAgo(instance: number): Date;
415
function minutesAgo(instance: number): Date;
416
function secondAgo(instance: number): Date;
417
function secondsAgo(instance: number): Date;
418
function weekAgo(instance: number): Date;
419
function weeksAgo(instance: number): Date;
420
function monthAgo(instance: number): Date;
421
function monthsAgo(instance: number): Date;
422
function yearAgo(instance: number): Date;
423
function yearsAgo(instance: number): Date;
424
425
/**
426
* Create dates relative to now (future)
427
*/
428
function dayFromNow(instance: number): Date;
429
function daysFromNow(instance: number): Date;
430
function hourFromNow(instance: number): Date;
431
function hoursFromNow(instance: number): Date;
432
function minuteFromNow(instance: number): Date;
433
function minutesFromNow(instance: number): Date;
434
function secondFromNow(instance: number): Date;
435
function secondsFromNow(instance: number): Date;
436
function weekFromNow(instance: number): Date;
437
function weeksFromNow(instance: number): Date;
438
function monthFromNow(instance: number): Date;
439
function monthsFromNow(instance: number): Date;
440
function yearFromNow(instance: number): Date;
441
function yearsFromNow(instance: number): Date;
442
443
/**
444
* Create dates relative to specific date (after)
445
* @param instance - Number of units
446
* @param date - Reference date
447
* @param options - Date creation options
448
* @returns Date after the reference date
449
*/
450
function dayAfter(instance: number, date: Date, options?: any): Date;
451
function daysAfter(instance: number, date: Date, options?: any): Date;
452
function hourAfter(instance: number, date: Date, options?: any): Date;
453
function hoursAfter(instance: number, date: Date, options?: any): Date;
454
function minuteAfter(instance: number, date: Date, options?: any): Date;
455
function minutesAfter(instance: number, date: Date, options?: any): Date;
456
function secondAfter(instance: number, date: Date, options?: any): Date;
457
function secondsAfter(instance: number, date: Date, options?: any): Date;
458
function weekAfter(instance: number, date: Date, options?: any): Date;
459
function weeksAfter(instance: number, date: Date, options?: any): Date;
460
function monthAfter(instance: number, date: Date, options?: any): Date;
461
function monthsAfter(instance: number, date: Date, options?: any): Date;
462
function yearAfter(instance: number, date: Date, options?: any): Date;
463
function yearsAfter(instance: number, date: Date, options?: any): Date;
464
465
/**
466
* Create dates relative to specific date (before)
467
* @param instance - Number of units
468
* @param date - Reference date
469
* @param options - Date creation options
470
* @returns Date before the reference date
471
*/
472
function dayBefore(instance: number, date: Date, options?: any): Date;
473
function daysBefore(instance: number, date: Date, options?: any): Date;
474
function hourBefore(instance: number, date: Date, options?: any): Date;
475
function hoursBefore(instance: number, date: Date, options?: any): Date;
476
function minuteBefore(instance: number, date: Date, options?: any): Date;
477
function minutesBefore(instance: number, date: Date, options?: any): Date;
478
function secondBefore(instance: number, date: Date, options?: any): Date;
479
function secondsBefore(instance: number, date: Date, options?: any): Date;
480
function weekBefore(instance: number, date: Date, options?: any): Date;
481
function weeksBefore(instance: number, date: Date, options?: any): Date;
482
function monthBefore(instance: number, date: Date, options?: any): Date;
483
function monthsBefore(instance: number, date: Date, options?: any): Date;
484
function yearBefore(instance: number, date: Date, options?: any): Date;
485
function yearsBefore(instance: number, date: Date, options?: any): Date;
486
```
487
488
**Usage Examples:**
489
490
```javascript
491
// Duration conversion (returns milliseconds)
492
(1).day(); // 86400000 (24 * 60 * 60 * 1000)
493
(2).hours(); // 7200000 (2 * 60 * 60 * 1000)
494
(30).minutes(); // 1800000 (30 * 60 * 1000)
495
(5).seconds(); // 5000
496
497
// Dates relative to now (past)
498
(2).daysAgo(); // Date 2 days ago
499
(3).hoursAgo(); // Date 3 hours ago
500
(1).weekAgo(); // Date 1 week ago
501
502
// Dates relative to now (future)
503
(5).daysFromNow(); // Date 5 days from now
504
(2).hoursFromNow(); // Date 2 hours from now
505
(1).monthFromNow(); // Date 1 month from now
506
507
// Dates relative to specific date
508
const baseDate = new Date('2023-01-15');
509
(3).daysAfter(baseDate); // 2023-01-18
510
(1).weekBefore(baseDate); // 2023-01-08
511
(6).monthsAfter(baseDate); // 2023-07-15
512
513
// Chaining with date operations
514
const futureDate = (2).weeksFromNow();
515
const pastDate = (5).daysBefore(futureDate);
516
```
517
518
## Types
519
520
```javascript { .api }
521
/**
522
* Map function type for transformation operations
523
*/
524
type mapFn<T, U> = (item: T, index?: number) => U;
525
```