-
Notifications
You must be signed in to change notification settings - Fork 8
/
ordinal.js
66 lines (59 loc) · 1.54 KB
/
ordinal.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
import { isInteger, isNil } from './utils';
import ordinalsuffix from './ordinalsuffix';
/**
* List of spelled out ordinals per AP style.
* @private
* @type {string[]}
*/
const AP_ORDINALS = [
'first',
'second',
'third',
'fourth',
'fifth',
'sixth',
'seventh',
'eighth',
'ninth',
];
/**
* Converts an integer into its ordinal form. If `spellOutOrdinals` is `true`,
* 1 through 9 will be spelled out per AP style. Handles the special cases of
* 11, 12 and 13, too. If a non-integer is submitted it will be returned in
* its original form.
*
* @param {number|string} val
* @param {boolean} [spellOutOrdinals]
* @return {string}
* @example
*
* var journalize = require('journalize');
*
* journalize.ordinal(5);
* // returns '5th'
*
* journalize.ordinal(13);
* // returns '13th'
*
* journalize.ordinal(103);
* // returns '103rd'
*
* journalize.ordinal(7, true);
* // returns 'seventh'
*/
export default function ordinal(val, spellOutOrdinals = false) {
// if `val` is undefined or null, return an empty string
if (isNil(val)) return '';
// ensure `val` is a number
const convertedVal = +val;
// if `convertedVal` is not an integer, return `val`
if (!isInteger(convertedVal)) return val.toString();
// if `spellOutOrdinals` is true, return the spelled out versions of 1-9
if (spellOutOrdinals && convertedVal < 10) {
return AP_ORDINALS[convertedVal - 1];
}
// get the suffix
const suffix = ordinalsuffix(convertedVal);
// return the original value with the suffix
return convertedVal + suffix;
}