-
Notifications
You must be signed in to change notification settings - Fork 8
/
addOrdinalSuffix.js
47 lines (40 loc) · 1.01 KB
/
addOrdinalSuffix.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
'use strict';
function mod10(num) {
return num % 10;
}
function mod100(num) {
return num % 100;
}
function isFirst(num) {
return mod10(num) === 1 && mod100(num) !== 11;
}
function isSecond(num) {
return mod10(num) === 2 && mod100(num) !== 12;
}
function isThird(num) {
return mod10(num) === 3 && mod100(num) !== 13;
}
/**
* add ordinal after a number
* e.g. `1` → `1st`, `2` → `2nd`, `3` → `3rd`
* @param {number|string} num number to add ordinal after
* @return {string}
*/
module.exports = function (num) {
// if no number is supplied, pass through string
if (num === '' || isNaN(num)) { // will check numbers and (numbers in) strings
return new String(num); // will convert to a string if it's a different type
} else if (isFirst(num)) {
return `${num}st`;
} else if (isSecond(num)) {
return `${num}nd`;
} else if (isThird(num)) {
return `${num}rd`;
} else {
return `${num}th`;
}
};
module.exports.example = {
code: '{{ addOrdinalSuffix 1 }}',
result: '1st'
};