diff --git a/README.md b/README.md index fcf52ea..fdc6472 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,12 @@ Qty.getUnits('currency'); // => [ 'dollar', 'cents' ] Qty.getUnits(); // => [ 'acre','Ah','ampere','AMU','angstrom'] ``` +### Alternative names of a unit + +```javascript +Qty.getAliases('m'); // => [ 'm', 'meter', 'meters', 'metre', 'metres' ] +``` + ### Quantity compatibility, kind and various queries ```javascript diff --git a/spec/quantitiesSpec.js b/spec/quantitiesSpec.js index e310558..d6a4ace 100644 --- a/spec/quantitiesSpec.js +++ b/spec/quantitiesSpec.js @@ -1251,6 +1251,14 @@ describe("js-quantities", function() { }); }); + describe("Qty.getAliases", function() { + it("should return array of alternative names for unit", function() { + expect(Qty.getAliases("m")).toContain("meter"); + expect(Qty.getAliases("meter")).toContain("metre"); + expect(Qty.getAliases("N")).toContain("newton"); + }); + }); + describe("information", function() { describe("bits and bytes", function() { it("should have 'information' as kind", function() { diff --git a/src/quantities.js b/src/quantities.js index 852cd15..1061d19 100644 --- a/src/quantities.js +++ b/src/quantities.js @@ -523,6 +523,20 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI }); }; + /** + * Returns a list of alternative names for a unit + * + * @param {string} unit + * @returns {string[]} aliases for unit + * @throws {QtyError} if unit is unknown + */ + Qty.getAliases = function(unitName) { + if (!UNIT_MAP[unitName]) { + throw new QtyError('Unit not recognized'); + } + return UNITS[UNIT_MAP[unitName]][0]; + }; + /** * Default formatter * @@ -1826,7 +1840,6 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI OUTPUT_MAP[unitDef] = definition[0][0]; } } - var PREFIX_REGEX = Object.keys(PREFIX_MAP).sort(function(a, b) { return b.length - a.length; }).join("|");