english-ordinals
Version:
Ordinal numbers in English: 1 => first etc.
61 lines • 2.39 kB
JavaScript
;
/**
* @license
* Copyright 2020 Ludan Stoecklé, 2015 Martin Eneqvist <marlun78@hotmail.com> (https://github.com/marlun78)
* SPDX-License-Identifier: MIT
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOrdinal = void 0;
// only import the exact file required (other it creates a huge browser bundle)
const n2words_EN_js_1 = __importDefault(require("../../rosaenlg-n2words/dist/n2words_EN.js"));
/*
more than largely inspired from https://github.com/marlun78/number-to-cardinal/blob/master/src/makeOrdinal.js
thanks to Martin Eneqvist the author
*/
const ENDS_WITH_DOUBLE_ZERO_PATTERN = /(hundred|thousand|(m|b|tr|quadr)illion)$/;
const ENDS_WITH_TEEN_PATTERN = /teen$/;
const ENDS_WITH_Y_PATTERN = /y$/;
const ENDS_WITH_ZERO_THROUGH_TWELVE_PATTERN = /(zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)$/;
const ordinalLessThanThirteen = {
zero: 'zeroth',
one: 'first',
two: 'second',
three: 'third',
four: 'fourth',
five: 'fifth',
six: 'sixth',
seven: 'seventh',
eight: 'eighth',
nine: 'ninth',
ten: 'tenth',
eleven: 'eleventh',
twelve: 'twelfth',
};
function getOrdinal(val) {
const cardinal = (0, n2words_EN_js_1.default)(val, { lang: 'en' });
// Ends with *00 (100, 1000, etc.) or *teen (13, 14, 15, 16, 17, 18, 19)
if (ENDS_WITH_DOUBLE_ZERO_PATTERN.test(cardinal) || ENDS_WITH_TEEN_PATTERN.test(cardinal)) {
return cardinal + 'th';
}
// Ends with *y (20, 30, 40, 50, 60, 70, 80, 90)
else if (ENDS_WITH_Y_PATTERN.test(cardinal)) {
return cardinal.replace(ENDS_WITH_Y_PATTERN, 'ieth');
} /* istanbul ignore next */
// Ends with one through twelve
else if (ENDS_WITH_ZERO_THROUGH_TWELVE_PATTERN.test(cardinal)) {
return cardinal.replace(ENDS_WITH_ZERO_THROUGH_TWELVE_PATTERN, (_match, numberWord) => {
// 'as' due to TypeScript 5
return ordinalLessThanThirteen[numberWord];
});
} /* istanbul ignore next */
else {
const err = new Error();
err.name = 'InvalidArgumentError';
err.message = `cannot make ordinal from ${cardinal}`;
}
}
exports.getOrdinal = getOrdinal;
//# sourceMappingURL=index.js.map