Skip to content

Instantly share code, notes, and snippets.

@darrylhebbes
Last active July 10, 2018 15:44
Show Gist options
  • Save darrylhebbes/dc3b49b4076072a1320b69ebb2a0f7e5 to your computer and use it in GitHub Desktop.
Save darrylhebbes/dc3b49b4076072a1320b69ebb2a0f7e5 to your computer and use it in GitHub Desktop.
My solution for returning the ordinal of a number, 2nd, 3rd, 4th
Array.range = (from, to, step) => Array.from(
{ length: Math.floor((to - from) / step) + 1 },
(v, k) => from + k * step
);
const testArr = Array.range(0,10,1);
const modulo = (x, n) => x % n;
// Check last two digits if are certain teens
const isTeenTh = n => [10, 11, 12, 13, 14, 15, 16, 17, 18, 19].includes(n % 100)
// for ordinal 'st'
const isModRestOne = (n, by) => modulo(n, by) === 1;
// for ordinal 'nt'
const isModRestTwo = (n, by) => modulo(n, by) === 2;
// for ordinal 'rd'
const isModRestThree = (n, by) => modulo(n, by) === 3;
const getOrdinal = n => {
if(!!isNaN(parseFloat(n)) && isFinite(n)) return NaN;
if (isModOne(n, 10) && !isTeenTh(n)) {
return `${n}st`;
}
if (isModTwo(n, 10) && !isTeenTh(n)) {
return `${n}nd`;
}
if (isModThree(n, 10) && !isTeenTh(n)) {
return `${n}rd`;
}
return n !== 0 ? `${n}th` : 0
}
const map = testArr.map((n, i) => {
return getOrdinal(n)
})
console.log(map)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment