Skip to content
This repository was archived by the owner on Feb 20, 2019. It is now read-only.

Commit 3d96524

Browse files
wsierakowskiKent C. Dodds
authored andcommitted
feat(getOrdinalSuffix): Add getOrdinalSuffix functionality (#130)
1 parent 97a7fa2 commit 3d96524

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

src/get-ordinal-suffix.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
export default getOrdinalSuffix
2+
3+
/**
4+
* Original source: https://stackoverflow.com/questions/13627308/add-st-nd-rd-and-th-ordinal-suffix-to-a-number
5+
* Adds ordinal suffix (st, nd, rd and th) to a number
6+
* @param {Number} num - number
7+
* @return {String} String representation of the number with the ordinal suffix
8+
*/
9+
10+
function getOrdinalSuffix(i) {
11+
const j = i % 10
12+
const k = i % 100
13+
if (j === 1 && k !== 11) {
14+
return `${i}st`
15+
}
16+
if (j === 2 && k !== 12) {
17+
return `${i}nd`
18+
}
19+
if (j === 3 && k !== 13) {
20+
return `${i}rd`
21+
}
22+
return `${i}th`
23+
}

src/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import convertToRoman from './convertToRoman'
4545
import gcd from './gcd'
4646
import range from './range'
4747
import contains from './contains'
48+
import getOrdinalSuffix from './get-ordinal-suffix'
4849

4950
export {
5051
isOdd,
@@ -94,4 +95,5 @@ export {
9495
gcd,
9596
range,
9697
contains,
98+
getOrdinalSuffix,
9799
}

test/get-ordinal-suffix.test.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import test from 'ava'
2+
import {getOrdinalSuffix} from '../src'
3+
4+
test('appends st, nd, th ordinal suffix to first 10 numbers', t => {
5+
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6+
const expected = ['0th', '1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th']
7+
const actual = numbers.map(n => getOrdinalSuffix(n))
8+
t.deepEqual(actual, expected)
9+
})
10+
11+
test('appends th ordinal suffix to second 10 numbers', t => {
12+
const numbers = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
13+
const expected = ['10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th']
14+
const actual = numbers.map(n => getOrdinalSuffix(n))
15+
t.deepEqual(actual, expected)
16+
})
17+
18+
test('appends st, nd, th ordinal suffix to third 10 numbers', t => {
19+
const numbers = [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
20+
const expected = ['20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th']
21+
const actual = numbers.map(n => getOrdinalSuffix(n))
22+
t.deepEqual(actual, expected)
23+
})

0 commit comments

Comments
 (0)