From 184e7d0e68e89e53bb993d6215af97f34adc4e6a Mon Sep 17 00:00:00 2001 From: Umair Ansari Date: Sat, 14 Mar 2020 12:26:26 -0700 Subject: [PATCH] Create pluralize.addRestoreCaseException fn which does not call restoreCase on specified tokens --- Readme.md | 5 +++++ pluralize.js | 17 +++++++++++++++-- test.js | 7 +++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index c000ada..df43a8f 100644 --- a/Readme.md +++ b/Readme.md @@ -81,6 +81,11 @@ pluralize.plural('paper') //=> "paper" // Example of asking whether a word looks singular or plural: pluralize.isPlural('test') //=> false pluralize.isSingular('test') //=> true + +// Example of adding a token exception whose case should not be restored: +pluralize.plural('promo ID') //=> 'promo IDS' +pluralize.addRestoreCaseException('IDs') +pluralize.plural('promo ID') //=> 'promo IDs' ``` ## License diff --git a/pluralize.js b/pluralize.js index 8528426..73e13e6 100644 --- a/pluralize.js +++ b/pluralize.js @@ -22,6 +22,7 @@ var uncountables = {}; var irregularPlurals = {}; var irregularSingles = {}; + var restoreCaseExceptions = []; /** * Sanitize a pluralization rule to a usable regular expression. @@ -31,7 +32,7 @@ */ function sanitizeRule (rule) { if (typeof rule === 'string') { - return new RegExp('^' + rule + '$', 'i'); + return new RegExp(rule + '$', 'i'); } return rule; @@ -46,6 +47,9 @@ * @return {Function} */ function restoreCase (word, token) { + // Do not restore the case of specified tokens + if (restoreCaseExceptions.indexOf(token) !== -1) return token; + // Tokens are an exact match. if (word === token) return token; @@ -115,7 +119,6 @@ // Iterate over the sanitization rules and use the first one to match. while (len--) { var rule = rules[len]; - if (rule[0].test(word)) return replace(word, rule); } @@ -225,6 +228,16 @@ pluralRules.push([sanitizeRule(rule), replacement]); }; + /** + * Add an exception to restoreCase. + * + * @param {string} exception + */ + + pluralize.addRestoreCaseException = function (exception) { + restoreCaseExceptions.push(exception); + }; + /** * Add a singularization rule to the collection. * diff --git a/test.js b/test.js index fc84d37..07503d2 100644 --- a/test.js +++ b/test.js @@ -832,5 +832,12 @@ describe('pluralize', function () { expect(pluralize.singular('mornings')).to.equal('suck'); }); + + it('will skip restoring case on specified token exceptions', function () { + expect(pluralize.plural('promo ID')).to.equal('promo IDS'); + pluralize.addRestoreCaseException('IDs'); + pluralize.addPluralRule('ID', 'IDs'); + expect(pluralize.plural('promo ID')).to.equal('promo IDs'); + }); }); });