forked from andrewplummer/Sugar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumber.js
438 lines (400 loc) · 12.1 KB
/
number.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
'use strict';
/***
* @package Number
* @dependency core
* @description Number formatting, rounding (with precision), and ranges. Aliases to Math methods.
*
***/
function getThousands() {
var str = sugarNumber.thousands;
return isString(str) ? str : ',';
}
function getDecimal() {
var str = sugarNumber.decimal;
return isString(str) ? str : '.';
}
function abbreviateNumber(num, roundTo, str, mid, limit, bytes) {
var fixed = num.toFixed(20),
decimalPlace = fixed.search(/\./),
numeralPlace = fixed.search(/[1-9]/),
significant = decimalPlace - numeralPlace,
unit, i, divisor;
if (significant > 0) {
significant -= 1;
}
i = max(min(floor(significant / 3), limit === false ? str.length : limit), -mid);
unit = str.charAt(i + mid - 1);
if (significant < -9) {
i = -3;
roundTo = abs(significant) - 9;
unit = str.slice(0,1);
}
divisor = bytes ? pow(2, 10 * i) : pow(10, i * 3);
return formatNumber(withPrecision(num / divisor, roundTo || 0)) + unit.trim();
}
function formatNumber(num, place) {
var i, str, split, integer, fraction, result = '';
var thousands = getThousands();
var decimal = getDecimal();
str = (isNumber(place) ? withPrecision(num, place || 0).toFixed(max(place, 0)) : num.toString()).replace(/^-/, '');
split = str.split('.');
integer = split[0];
fraction = split[1];
for(i = integer.length; i > 0; i -= 3) {
if (i < integer.length) {
result = thousands + result;
}
result = integer.slice(max(0, i - 3), i) + result;
}
if (fraction) {
result += decimal + repeatString('0', (place || 0) - fraction.length) + fraction;
}
return (num < 0 ? '-' : '') + result;
}
function isInteger(n) {
return n % 1 === 0;
}
function isMultiple(n1, n2) {
return n1 % n2 === 0;
}
extend(number, {
/***
* @method Number.random([n1], [n2])
* @returns Number
* @short Returns a random integer between [n1] and [n2].
* @extra If only 1 number is passed, the other will be 0. If none are passed, the number will be either 0 or 1.
* @example
*
* Number.random(50, 100) -> ex. 85
* Number.random(50) -> ex. 27
* Number.random() -> ex. 0
*
***/
'random': function(n1, n2) {
var minNum, maxNum;
if (arguments.length == 1) n2 = n1, n1 = 0;
minNum = min(n1 || 0, isUndefined(n2) ? 1 : n2);
maxNum = max(n1 || 0, isUndefined(n2) ? 1 : n2) + 1;
return floor((math.random() * (maxNum - minNum)) + minNum);
}
}, false);
extend(number, {
/***
* @method Number.isNaN(<value>)
* @returns Boolean
* @short Returns true only if the number is %NaN%.
* @extra This is differs from the global %isNaN%, which returns true for anything that is not a number.
* @example
*
* Number.isNaN(NaN) -> true
* Number.isNaN('n') -> false
*
***/
'isNaN': function(value) {
return value !== value;
}
}, false, true);
extend(number, {
/***
* @method log(<base> = Math.E)
* @returns Number
* @short Returns the logarithm of the number with base <base>, or natural logarithm of the number if <base> is undefined.
* @example
*
* (64).log(2) -> 6
* (9).log(3) -> 2
* (5).log() -> 1.6094379124341003
*
***/
'log': function(base) {
return math.log(this) / (base ? math.log(base) : 1);
},
/***
* @method abbr([precision] = 0)
* @returns String
* @short Returns an abbreviated form of the number.
* @extra [precision] will round to the given precision. %Sugar.Number.thousands% and %Sugar.Number.decimal% allow custom markers to be used.
* @example
*
* (1000).abbr() -> "1k"
* (1000000).abbr() -> "1m"
* (1280).abbr(1) -> "1.3k"
*
***/
'abbr': function(precision) {
return abbreviateNumber(this, precision, 'kmbt', 0, 4);
},
/***
* @method metric([precision] = 0, [limit] = 1)
* @returns String
* @short Returns the number as a string in metric notation.
* @extra [precision] will round to the given precision. Both very large numbers and very small numbers are supported. [limit] is the upper limit for the units. The default is %1%, which is "kilo". If [limit] is %false%, the upper limit will be "exa". The lower limit is "nano", and cannot be changed. %Sugar.Number.thousands% and %Sugar.Number.decimal% allow custom markers to be used.
* @example
*
* (1000).metric() -> "1k"
* (1000000).metric() -> "1,000k"
* (1000000).metric(0, false) -> "1M"
* (1249).metric(2) + 'g' -> "1.25kg"
* (0.025).metric() + 'm' -> "25mm"
*
***/
'metric': function(precision, limit) {
return abbreviateNumber(this, precision, 'nμm kMGTPE', 4, isUndefined(limit) ? 1 : limit);
},
/***
* @method bytes([precision] = 0, [limit] = 4, [si] = false)
* @returns String
* @short Returns an abbreviated form of the number, considered to be "Bytes".
* @extra [precision] will round to the given precision. [limit] is the upper limit for the units. The default is %4%, which is "terabytes" (TB). If [limit] is %false%, the upper limit will be "exa". If [si] is %true%, the standard SI units of 1000 will be used instead of 1024. %Sugar.Number.thousands% and %Sugar.Number.decimal% allow custom markers to be used.
* @example
*
* (1000).bytes() -> "1kB"
* (1000).bytes(2) -> "0.98kB"
* ((10).pow(20)).bytes() -> "90,949,470TB"
* ((10).pow(20)).bytes(0, false) -> "87EB"
*
***/
'bytes': function(precision, limit, si) {
return abbreviateNumber(this, precision, 'kMGTPE', 0, isUndefined(limit) ? 4 : limit, si !== true) + 'B';
},
/***
* @method isInteger()
* @returns Boolean
* @short Returns true if the number has no trailing decimal.
* @example
*
* (420).isInteger() -> true
* (4.5).isInteger() -> false
*
***/
'isInteger': function() {
return isInteger(this);
},
/***
* @method isOdd()
* @returns Boolean
* @short Returns true if the number is odd.
* @example
*
* (3).isOdd() -> true
* (18).isOdd() -> false
*
***/
'isOdd': function() {
return isInteger(this) && !isMultiple(this, 2);
},
/***
* @method isEven()
* @returns Boolean
* @short Returns true if the number is even.
* @example
*
* (6).isEven() -> true
* (17).isEven() -> false
*
***/
'isEven': function() {
return isMultiple(this, 2);
},
/***
* @method isMultipleOf(<num>)
* @returns Boolean
* @short Returns true if the number is a multiple of <num>.
* @example
*
* (6).isMultipleOf(2) -> true
* (17).isMultipleOf(2) -> false
* (32).isMultipleOf(4) -> true
* (34).isMultipleOf(4) -> false
*
***/
'isMultipleOf': function(num) {
return isMultiple(this, num);
},
/***
* @method format([place] = 0)
* @returns String
* @short Formats the number to a readable string.
* @extra If [place] is %undefined%, the place will automatically be determined. %Sugar.Number.thousands% and %Sugar.Number.decimal% allow custom markers to be used.
* @example
*
* (56782).format() -> '56,782'
* (56782).format(2) -> '56,782.00'
* (4388.43).format(2) -> '4,388.43'
*
***/
'format': function(place) {
return formatNumber(this, place);
},
/***
* @method hex([pad] = 1)
* @returns String
* @short Converts the number to hexidecimal.
* @extra [pad] will pad the resulting string to that many places.
* @example
*
* (255).hex() -> 'ff';
* (255).hex(4) -> '00ff';
* (23654).hex() -> '5c66';
*
***/
'hex': function(pad) {
return padNumber(this, pad || 1, false, 16);
},
/***
* @method times(<fn>)
* @returns Number
* @short Calls <fn> a number of times equivalent to the number.
* @example
*
* (8).times(function(i) {
* // This function is called 8 times.
* });
*
***/
'times': function(fn) {
if (fn) {
for(var i = 0; i < this; i++) {
fn.call(this, i);
}
}
return +this;
},
/***
* @method chr()
* @returns String
* @short Returns a string at the code point of the number.
* @example
*
* (65).chr() -> "A"
* (75).chr() -> "K"
*
***/
'chr': function() {
return string.fromCharCode(this);
},
/***
* @method pad(<place> = 0, [sign] = false, [base] = 10)
* @returns String
* @short Pads a number with "0" to <place>.
* @extra [sign] allows you to force the sign as well (+05, etc). [base] can change the base for numeral conversion.
* @example
*
* (5).pad(2) -> '05'
* (-5).pad(4) -> '-0005'
* (82).pad(3, true) -> '+082'
*
***/
'pad': function(place, sign, base) {
return padNumber(this, place, sign, base);
},
/***
* @method ordinalize()
* @returns String
* @short Returns an ordinalized (English) string, i.e. "1st", "2nd", etc.
* @example
*
* (1).ordinalize() -> '1st';
* (2).ordinalize() -> '2nd';
* (8).ordinalize() -> '8th';
*
***/
'ordinalize': function() {
var suffix, num = abs(this), last = parseInt(num.toString().slice(-2));
return this + getOrdinalizedSuffix(last);
},
/***
* @method toNumber()
* @returns Number
* @short Returns a number. This is mostly for compatibility reasons.
* @example
*
* (420).toNumber() -> 420
*
***/
'toNumber': function() {
return parseFloat(this, 10);
}
});
/***
* @method round(<precision> = 0)
* @returns Number
* @short Shortcut for %Math.round% that also allows a <precision>.
*
* @example
*
* (3.241).round() -> 3
* (-3.841).round() -> -4
* (3.241).round(2) -> 3.24
* (3748).round(-2) -> 3800
*
***
* @method ceil(<precision> = 0)
* @returns Number
* @short Shortcut for %Math.ceil% that also allows a <precision>.
*
* @example
*
* (3.241).ceil() -> 4
* (-3.241).ceil() -> -3
* (3.241).ceil(2) -> 3.25
* (3748).ceil(-2) -> 3800
*
***
* @method floor(<precision> = 0)
* @returns Number
* @short Shortcut for %Math.floor% that also allows a <precision>.
*
* @example
*
* (3.241).floor() -> 3
* (-3.841).floor() -> -4
* (3.241).floor(2) -> 3.24
* (3748).floor(-2) -> 3700
*
***
* @method [math]()
* @returns Number
* @short Math related functions are mapped as shortcuts to numbers and are identical. Note that %Number#log% provides some special defaults.
*
* @set
* abs
* sin
* asin
* cos
* acos
* tan
* atan
* sqrt
* exp
* pow
*
* @example
*
* (3).pow(3) -> 27
* (-3).abs() -> 3
* (1024).sqrt() -> 32
*
***/
function buildNumber() {
function createRoundingFunction(fn) {
return function (precision) {
return precision ? withPrecision(this, precision, fn) : fn(this);
}
}
extend(number, {
'ceil': createRoundingFunction(ceil),
'round': createRoundingFunction(round),
'floor': createRoundingFunction(floor)
});
extendSimilar(number, 'abs,pow,sin,asin,cos,acos,tan,atan,exp,pow,sqrt', function(methods, name) {
methods[name] = function(a, b) {
// Note that .valueOf() here is only required due to a
// very strange bug in iOS7 that only occurs occasionally
// in which Math.abs() called on non-primitive numbers
// returns a completely different number (Issue #400)
return math[name](this.valueOf(), a, b);
}
});
}
buildNumber();