-
Notifications
You must be signed in to change notification settings - Fork 75
/
humanize.js
483 lines (397 loc) · 14.2 KB
/
humanize.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
/**
* Copyright 2013-2016 HubSpotDev
* MIT Licensed
*
* @module humanize.js
*/
((root, factory) => {
if (typeof exports === 'object') {
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
define([], () => (root.Humanize = factory()));
} else {
root.Humanize = factory();
}
})(this, () => {
//------------------------------------------------------------------------------
// Constants
//------------------------------------------------------------------------------
const TIME_FORMATS = [
{
name: 'second',
value: 1e3
},
{
name: 'minute',
value: 6e4
},
{
name: 'hour',
value: 36e5
},
{
name: 'day',
value: 864e5
},
{
name: 'week',
value: 6048e5
}
];
const LABELS_FOR_POWERS_OF_KILO = {
P: Math.pow(2, 50),
T: Math.pow(2, 40),
G: Math.pow(2, 30),
M: Math.pow(2, 20)
};
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const exists = maybe => typeof maybe !== 'undefined' && maybe !== null;
const isNaN = value => value !== value; // eslint-disable-line
const isFiniteNumber = value => {
return isFinite(value) && !isNaN(parseFloat(value));
};
const isArray = value => {
const type = Object.prototype.toString.call(value);
return type === '[object Array]';
};
//------------------------------------------------------------------------------
// Humanize
//------------------------------------------------------------------------------
const Humanize = {
// Converts a large integer to a friendly text representation.
intword(number, charWidth, decimals = 2) {
/*
* This method is deprecated. Please use compactInteger instead.
* intword will be going away in the next major version.
*/
return Humanize.compactInteger(number, decimals);
},
// Converts an integer into its most compact representation
compactInteger(input, decimals = 0) {
decimals = Math.max(decimals, 0);
const number = parseInt(input, 10);
const signString = number < 0 ? '-' : '';
const unsignedNumber = Math.abs(number);
const unsignedNumberString = String(unsignedNumber);
const numberLength = unsignedNumberString.length;
const numberLengths = [13, 10, 7, 4];
const bigNumPrefixes = ['T', 'B', 'M', 'k'];
// small numbers
if (unsignedNumber < 1000) {
return `${ signString }${ unsignedNumberString }`;
}
// really big numbers
if (numberLength > numberLengths[0] + 3) {
return number.toExponential(decimals).replace('e+', 'x10^');
}
// 999 < unsignedNumber < 999,999,999,999,999
let length;
for (let i = 0; i < numberLengths.length; i++) {
const _length = numberLengths[i];
if (numberLength >= _length) {
length = _length;
break;
}
}
const decimalIndex = numberLength - length + 1;
const unsignedNumberCharacterArray = unsignedNumberString.split('');
const wholePartArray = unsignedNumberCharacterArray.slice(0, decimalIndex);
const decimalPartArray = unsignedNumberCharacterArray.slice(decimalIndex, decimalIndex + decimals + 1);
const wholePart = wholePartArray.join('');
// pad decimalPart if necessary
let decimalPart = decimalPartArray.join('');
if (decimalPart.length < decimals) {
decimalPart += `${ Array(decimals - decimalPart.length + 1).join('0') }`;
}
let output;
if (decimals === 0) {
output = `${ signString }${ wholePart }${ bigNumPrefixes[numberLengths.indexOf(length)] }`;
} else {
const outputNumber = Number(`${ wholePart }.${ decimalPart }`).toFixed(decimals);
output = `${ signString }${ outputNumber }${ bigNumPrefixes[numberLengths.indexOf(length)] }`;
}
return output;
},
// Converts an integer to a string containing commas every three digits.
intComma(number, decimals = 0) {
return Humanize.formatNumber(number, decimals);
},
intcomma(...args) {
return Humanize.intComma(...args);
},
// Formats the value like a 'human-readable' file size (i.e. '13 KB', '4.1 MB', '102 bytes', etc).
fileSize(filesize, precision = 2) {
for (const label in LABELS_FOR_POWERS_OF_KILO) {
if (LABELS_FOR_POWERS_OF_KILO.hasOwnProperty(label)) {
const minnum = LABELS_FOR_POWERS_OF_KILO[label];
if (filesize >= minnum) {
return `${Humanize.formatNumber(filesize / minnum, precision, '')} ${label}B`;
}
}
}
if (filesize >= 1024) {
return `${Humanize.formatNumber(filesize / 1024, 0)} KB`;
}
return Humanize.formatNumber(filesize, 0) + Humanize.pluralize(filesize, ' byte');
},
filesize(...args) {
return Humanize.fileSize(...args);
},
// Formats a number to a human-readable string.
// Localize by overriding the precision, thousand and decimal arguments.
formatNumber(number, precision = 0, thousand = ',', decimal = '.') {
// Create some private utility functions to make the computational
// code that follows much easier to read.
const firstComma = (_number, _thousand, _position) => {
return _position ? _number.substr(0, _position) + _thousand : '';
};
const commas = (_number, _thousand, _position) => {
return _number.substr(_position).replace(/(\d{3})(?=\d)/g, `$1${_thousand}`);
};
const decimals = (_number, _decimal, usePrecision) => {
return usePrecision
? _decimal + Humanize.toFixed(Math.abs(_number), usePrecision).split('.')[1]
: '';
};
const usePrecision = Humanize.normalizePrecision(precision);
// Do some calc
const negative = number < 0 && '-' || '';
const base = String(parseInt(Humanize.toFixed(Math.abs(number || 0), usePrecision), 10));
const mod = base.length > 3 ? base.length % 3 : 0;
// Format the number
return (
negative +
firstComma(base, thousand, mod) +
commas(base, thousand, mod) +
decimals(number, decimal, usePrecision)
);
},
// Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61')
toFixed(value, precision) {
precision = exists(precision) ? precision : Humanize.normalizePrecision(precision, 0);
const power = Math.pow(10, precision);
// Multiply up by precision, round accurately, then divide and use native toFixed()
return (Math.round(value * power) / power).toFixed(precision);
},
// Ensures precision value is a positive integer
normalizePrecision(value, base) {
value = Math.round(Math.abs(value));
return isNaN(value) ? base : value;
},
// Converts an integer to its ordinal as a string.
ordinal(value) {
const number = parseInt(value, 10);
if (number === 0) {
return value;
}
const specialCase = number % 100;
if ([11, 12, 13].indexOf(specialCase) >= 0) {
return `${ number }th`;
}
const leastSignificant = number % 10;
let end;
switch (leastSignificant) {
case 1:
end = 'st';
break;
case 2:
end = 'nd';
break;
case 3:
end = 'rd';
break;
default:
end = 'th';
}
return `${ number }${ end }`;
},
// Interprets numbers as occurences. Also accepts an optional array/map of overrides.
times(value, overrides = {}) {
if (isFiniteNumber(value) && value >= 0) {
const number = parseFloat(value);
const smallTimes = ['never', 'once', 'twice'];
if (exists(overrides[number])) {
return String(overrides[number]);
}
const numberString = exists(smallTimes[number]) && smallTimes[number].toString();
return numberString || `${number.toString()} times`;
}
return null;
},
// Returns the plural version of a given word if the value is not 1. The default suffix is 's'.
pluralize(number, singular, plural) {
if (!(exists(number) && exists(singular))) {
return null;
}
plural = exists(plural) ? plural : `${singular}s`;
return parseInt(number, 10) === 1 ? singular : plural;
},
// Truncates a string if it is longer than the specified number of characters (inclusive).
// Truncated strings will end with a translatable ellipsis sequence ("…").
truncate(str, length = 100, ending = '...') {
if (str.length > length) {
return str.substring(0, length - ending.length) + ending;
}
return str;
},
// Truncates a string after a certain number of words.
truncateWords(string, length) {
const array = string.split(' ');
let result = '';
let i = 0;
while (i < length) {
if (exists(array[i])) {
result += `${array[i]} `;
}
i++;
}
if (array.length > length) {
return `${result}...`;
}
return null;
},
truncatewords(...args) {
return Humanize.truncateWords(...args);
},
// Truncates a number to an upper bound.
boundedNumber(num, bound = 100, ending = '+') {
let result;
if (isFiniteNumber(num) && isFiniteNumber(bound)) {
if (num > bound) {
result = bound + ending;
}
}
return (result || num).toString();
},
truncatenumber(...args) {
return Humanize.boundedNumber(...args);
},
// Converts a list of items to a human readable string with an optional limit.
oxford(items, limit, limitStr) {
const numItems = items.length;
let limitIndex;
if (numItems < 2) {
return String(items);
} else if (numItems === 2) {
return items.join(' and ');
} else if (exists(limit) && numItems > limit) {
const extra = numItems - limit;
limitIndex = limit;
limitStr = exists(limitStr) ? limitStr : `, and ${extra} ${Humanize.pluralize(extra, 'other')}`;
} else {
limitIndex = -1;
limitStr = `, and ${items[numItems - 1]}`;
}
return items.slice(0, limitIndex).join(', ') + limitStr;
},
// Converts an object to a definition-like string
dictionary(object, joiner = ' is ', separator = ', ') {
const result = '';
if (exists(object) && typeof object === 'object' && !isArray(object)) {
const defs = [];
for (const key in object) {
if (object.hasOwnProperty(key)) {
const val = object[key];
defs.push(`${ key }${ joiner }${ val }`);
}
}
return defs.join(separator);
}
return result;
},
// Describes how many times an item appears in a list
frequency(list, verb) {
if (!isArray(list)) {
return null;
}
const len = list.length;
const times = Humanize.times(len);
if (len === 0) {
return `${times} ${verb}`;
}
return `${verb} ${times}`;
},
pace(value, intervalMs, unit = 'time') {
if (value === 0 || intervalMs === 0) {
// Needs a better string than this...
return `No ${Humanize.pluralize(0, unit)}`;
}
// Expose these as overridables?
let prefix = 'Approximately';
let timeUnit;
let relativePace;
const rate = value / intervalMs;
for (let i = 0; i < TIME_FORMATS.length; ++i) { // assumes sorted list
const f = TIME_FORMATS[i];
relativePace = rate * f.value;
if (relativePace > 1) {
timeUnit = f.name;
break;
}
}
// Use the last time unit if there is nothing smaller
if (!timeUnit) {
prefix = 'Less than';
relativePace = 1;
timeUnit = TIME_FORMATS[TIME_FORMATS.length - 1].name;
}
const roundedPace = Math.round(relativePace);
unit = Humanize.pluralize(roundedPace, unit);
return `${prefix} ${roundedPace} ${unit} per ${timeUnit}`;
},
// Converts newlines to <br/> tags
nl2br(string, replacement = '<br/>') {
return string.replace(/\n/g, replacement);
},
// Converts <br/> tags to newlines
br2nl(string, replacement = '\r\n') {
return string.replace(/\<br\s*\/?\>/g, replacement);
},
// Capitalizes first letter in a string
capitalize(string, downCaseTail = false) {
return `${ string.charAt(0).toUpperCase() }${ downCaseTail ? string.slice(1).toLowerCase() : string.slice(1) }`;
},
// Capitalizes the first letter of each word in a string
capitalizeAll(string) {
return string.replace(/(?:^|\s)\S/g, (a) => a.toUpperCase());
},
// Titlecase words in a string.
titleCase(string) {
const smallWords = /\b(a|an|and|at|but|by|de|en|for|if|in|of|on|or|the|to|via|vs?\.?)\b/i;
const internalCaps = /\S+[A-Z]+\S*/;
const splitOnWhiteSpaceRegex = /\s+/;
const splitOnHyphensRegex = /-/;
let doTitleCase;
doTitleCase = (_string, hyphenated = false, firstOrLast = true) => {
const titleCasedArray = [];
const stringArray = _string.split(hyphenated ? splitOnHyphensRegex : splitOnWhiteSpaceRegex);
for (let index = 0; index < stringArray.length; ++index) {
const word = stringArray[index];
if (word.indexOf('-') !== -1) {
titleCasedArray.push(doTitleCase(word, true, (index === 0 || index === stringArray.length - 1)));
continue;
}
if (firstOrLast && (index === 0 || index === stringArray.length - 1)) {
titleCasedArray.push(internalCaps.test(word) ? word : Humanize.capitalize(word));
continue;
}
if (internalCaps.test(word)) {
titleCasedArray.push(word);
} else if (smallWords.test(word)) {
titleCasedArray.push(word.toLowerCase());
} else {
titleCasedArray.push(Humanize.capitalize(word));
}
}
return titleCasedArray.join(hyphenated ? '-' : ' ');
};
return doTitleCase(string);
},
titlecase(...args) {
return Humanize.titleCase(...args);
}
};
return Humanize;
});