diff --git a/README.md b/README.md index 13ca50c..de02509 100644 --- a/README.md +++ b/README.md @@ -256,6 +256,25 @@ var qty = Qty('1.1234 m'); qty.format(); // same units, current default formatter => '1.12 m' ``` +### Unit names + +Unit names can be extracted using `Qty#getUnits`, which returns an object with +all available unit names, including prefixes, and their synonyms, categorized by +kind. Can optionally be restricted to only one kind. + +```javascript +var units = Qty.getUnits(); // dictionary containing all units, by category + // { ..., + // length: { m: ["m","meter","meters", + // "metre","metres"], ...}, + // ... } + +var lengthUnits = Qty.getUnits("length"); // dictionary containing all length + // units + // { m: ["m","meter","meters","metre", + // "metres"] } +``` + ### Temperatures Like ruby-units, JS-quantities makes a distinction between a temperature (which diff --git a/spec/quantitiesSpec.js b/spec/quantitiesSpec.js index 6b51528..2c9b194 100644 --- a/spec/quantitiesSpec.js +++ b/spec/quantitiesSpec.js @@ -1154,4 +1154,24 @@ describe("js-quantities", function() { }); }); + describe("Qty.getUnits", function() { + it("should return a populated > dictionary of all unit names", function() { + var units = Qty.getUnits(), + expectedKey = "meter", + expectedValue = ["m","meter","meters","metre","metres"]; + + expect(units.length[expectedKey]).toEqual(expectedValue); + }); + + it ("should optionally restrict returned units to one kind", function() { + var resistanceUnits = Qty.getUnits("resistance"), + unexpectedKey = "meter", + expectedKey = "ohm", + expectedValue = ["Ohm", "ohm"]; + + expect(Object.keys(resistanceUnits).indexOf(unexpectedKey)).toBe(-1); + expect(resistanceUnits[expectedKey]).toEqual(expectedValue); + }); + }); + }); diff --git a/src/quantities.js b/src/quantities.js index 35eae4e..8e3cabb 100644 --- a/src/quantities.js +++ b/src/quantities.js @@ -452,6 +452,35 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI }; }; + /** + * Returns an object with the names of the available units, categorized by + * kind. Can optionally be restricted to only one kind. + * + * @param {string} kind optionally restrict to this kind + * @returns {Object} unit names + */ + Qty.getUnits = function(kind) { + var kinds = {}, + k; + for (var unitId in UNITS) { + k = UNITS[unitId][2]; + if (k.length === 0) { + continue; + } + if (kinds[k] === undefined) { + kinds[k] = {}; + } + kinds[k][unitId.substr(1, unitId.length - 2)] = UNITS[unitId][0]; + } + if (kind) { + if (kinds[kind] === undefined) { + throw new QtyError(kind + ": Kind not recognized."); + } + return kinds[kind]; + } + return kinds; + }; + /** * Default formatter *