@lhncbc/ucum-lhc 4.1.7 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/browser-dist/ucum-lhc.js +156 -52
- package/package.json +2 -1
- package/source/config.js +3 -2
- package/source/ucumLhcUtils.js +70 -0
- package/source/unit.js +28 -34
- package/source/unitString.js +29 -13
- package/source/unitTables.js +14 -0
- package/source-cjs/config.js +2 -2
- package/source-cjs/config.js.map +1 -1
- package/source-cjs/ucumLhcUtils.js +70 -0
- package/source-cjs/ucumLhcUtils.js.map +1 -1
- package/source-cjs/unit.js +27 -36
- package/source-cjs/unit.js.map +1 -1
- package/source-cjs/unitString.js +29 -9
- package/source-cjs/unitString.js.map +1 -1
- package/source-cjs/unitTables.js +16 -0
- package/source-cjs/unitTables.js.map +1 -1
- package/CHANGELOG.md +0 -329
package/source-cjs/config.js
CHANGED
|
@@ -65,14 +65,14 @@ var Ucum = {
|
|
|
65
65
|
* displaying messages on a web site; should be blank when output is
|
|
66
66
|
* to a file.
|
|
67
67
|
*/
|
|
68
|
-
openEmphHTML_: '<span class="emphSpan">',
|
|
68
|
+
openEmphHTML_: ' <span class="emphSpan">',
|
|
69
69
|
|
|
70
70
|
/**
|
|
71
71
|
* Closing HTML used to emphasize portions of error messages. Used when
|
|
72
72
|
* displaying messages on a web site; should be blank when output is
|
|
73
73
|
* to a file.
|
|
74
74
|
*/
|
|
75
|
-
closeEmphHTML_: '</span>',
|
|
75
|
+
closeEmphHTML_: '</span> ',
|
|
76
76
|
|
|
77
77
|
/**
|
|
78
78
|
* Message that is displayed when annotations are included in a unit
|
package/source-cjs/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../source/config.js"],"names":["Ucum","dimLen_","validOps_","codeSep_","valMsgStart_","valMsgEnd_","cnvMsgStart_","cnvMsgEnd_","openEmph_","closeEmph_","openEmphHTML_","closeEmphHTML_","bracesMsg_","needMoleWeightMsg_","csvCols_","inputKey_","specUnits_"],"mappings":";;;;;;;AAAA;;;;;;;AAQO,IAAIA,IAAI,GAAG;AAEhB;;;;;;AAMA;;AAEA;;;;;;AAMAC,EAAAA,OAAO,EAAE,CAhBO;;
|
|
1
|
+
{"version":3,"sources":["../source/config.js"],"names":["Ucum","dimLen_","validOps_","codeSep_","valMsgStart_","valMsgEnd_","cnvMsgStart_","cnvMsgEnd_","openEmph_","closeEmph_","openEmphHTML_","closeEmphHTML_","bracesMsg_","needMoleWeightMsg_","csvCols_","inputKey_","specUnits_"],"mappings":";;;;;;;AAAA;;;;;;;AAQO,IAAIA,IAAI,GAAG;AAEhB;;;;;;AAMA;;AAEA;;;;;;AAMAC,EAAAA,OAAO,EAAE,CAhBO;;AAmBhB;;;;AAIAC,EAAAA,SAAS,EAAE,CAAC,GAAD,EAAM,GAAN,CAvBK;;AA0BhB;;;;AAIAC,EAAAA,QAAQ,EAAG,IA9BK;AAgChB;AACAC,EAAAA,YAAY,EAAG,eAjCC;AAkChBC,EAAAA,UAAU,EAAG,GAlCG;AAmChBC,EAAAA,YAAY,EAAG,uBAnCC;AAoChBC,EAAAA,UAAU,EAAG,GApCG;;AAuClB;;;;;AAKEC,EAAAA,SAAS,EAAG,KA5CI;;AA8ChB;;;;;AAKAC,EAAAA,UAAU,EAAG,KAnDG;;AAqDhB;;;;;AAKAC,EAAAA,aAAa,EAAG,0BA1DA;;AA4DhB;;;;;AAKAC,EAAAA,cAAc,EAAG,UAjED;;AAmEhB;;;;AAIAC,EAAAA,UAAU,EAAG,8DACA,6DADA,GAEA,iCAzEG;;AA2EhB;;;;;AAKAC,EAAAA,kBAAkB,EAAG,0DACA,uDADA,GAEA,8CAlFL;;AAoFhB;;;;AAIAC,EAAAA,QAAQ,EAAG;AACT,2BAAwB,SADf;AAET,sBAAmB,gBAFV;AAGT,sBAAmB,OAHV;AAIT,gBAAa,WAJJ;AAKT,cAAW,SALF;AAMT,gBAAa,WANJ;AAOT,gBAAa;AAPJ,GAxFK;;AAkGhB;;;AAGAC,EAAAA,SAAS,EAAG,qBArGI;;AAuGhB;;;;;;;AAOCC,EAAAA,UAAU,EAAG;AAAE,gBAAa,gBAAf;AACE,uBAAoB;AADtB;AA9GE,CAAX","sourcesContent":["/*\n * This defines the namespace for the UCUM classes and provides\n * a place for the definition of global variables and constants.\n *\n * The javascript for this UCUM implementation uses syntax as\n * defined by the ECMAScript 6 standard\n */\n\nexport var Ucum = {\n\n /**\n * Flag indicating whether or not we're using case sensitive labels\n * I don't think we need this. I think we're just going with\n * case sensitive, per Clem. Gunther's code has this flag, but I\n * am removing it, at least for now. lm, 6/2016\n */\n //caseSensitive_: true ,\n\n /**\n * The number of elements in a Dimension array. Currently this\n * is set as a configuration variable, but when we get to the point\n * of loading the unit definitions from a file, this value will be\n * set from that.\n */\n dimLen_: 7,\n\n\n /**\n * The characters used as valid operators in a UCUM unit expression,\n * where '.' is for multiplication and '/' is for division.\n */\n validOps_: ['.', '/'],\n\n\n /**\n * The string used to separate a unit code and unit name when they\n * are displayed together\n */\n codeSep_ : ': ',\n\n // Message text variations for validation methods and conversion methods\n valMsgStart_ : 'Did you mean ',\n valMsgEnd_ : '?' ,\n cnvMsgStart_ : 'We assumed you meant ',\n cnvMsgEnd_ : '.',\n\n\n/**\n * Default opening string used to emphasize portions of error messages.\n * Used when NOT displaying messages on a web site, i.e., for output\n * from the library methods or to a file.\n */\n openEmph_ : ' ->',\n\n /**\n * Default closing string used to emphasize portions of error messages.\n * Used when NOT displaying messages on a web site, i.e., for output\n * from the library methods or to a file.\n */\n closeEmph_ : '<- ' ,\n\n /**\n * Opening HTML used to emphasize portions of error messages. Used when\n * displaying messages on a web site; should be blank when output is\n * to a file.\n */\n openEmphHTML_ : ' <span class=\"emphSpan\">',\n\n /**\n * Closing HTML used to emphasize portions of error messages. Used when\n * displaying messages on a web site; should be blank when output is\n * to a file.\n */\n closeEmphHTML_ : '</span> ' ,\n\n /**\n * Message that is displayed when annotations are included in a unit\n * string, to let the user know how they are interpreted.\n */\n bracesMsg_ : 'FYI - annotations (text in curly braces {}) are ignored, ' +\n 'except that an annotation without a leading symbol implies ' +\n 'the default unit 1 (the unity).',\n\n /**\n * Message that is displayed or returned when a conversion is requested\n * for two units where (only) a mass<->moles conversion is appropriate\n * but no molecular weight was specified.\n */\n needMoleWeightMsg_ : 'Did you wish to convert between mass and moles? The ' +\n 'molecular weight of the substance represented by the ' +\n 'units is required to perform the conversion.',\n\n /**\n * Hash that matches unit column names to names used in the csv file\n * that is submitted to the data updater.\n */\n csvCols_ : {\n 'case-sensitive code' : 'csCode_',\n 'LOINC property' : 'loincProperty_',\n 'name (display)' : 'name_',\n 'synonyms' : 'synonyms_',\n 'source' : 'source_',\n 'category' : 'category_',\n 'Guidance' : 'guidance_'\n } ,\n\n /**\n * Name of the column in the csv file that serves as the key\n */\n inputKey_ : 'case-sensitive code' ,\n\n /**\n * Special codes that contain operators within brackets. The operator\n * within these codes causes them to parse incorrectly if they are preceded\n * by a prefix, because the parsing algorithm splits them up on the operator.\n * So we use this object to identify them and substitute placeholders to\n * avoid that.\n */\n specUnits_ : { 'B[10.nV]' : 'specialUnitOne',\n '[m/s2/Hz^(1/2)]' : 'specialUnitTwo'}\n} ;\n\n\n"],"file":"config.js"}
|
|
@@ -333,6 +333,76 @@ class UcumLhcUtils {
|
|
|
333
333
|
return returnObj;
|
|
334
334
|
} // end convertUnitTo
|
|
335
335
|
|
|
336
|
+
/**
|
|
337
|
+
* Converts the given unit string into its base units, their exponents, and
|
|
338
|
+
* a magnitude, and returns that data.
|
|
339
|
+
* @param fromUnit the unit string to be converted to base units information
|
|
340
|
+
* @param fromVal the number of "from" units to be converted
|
|
341
|
+
* @returns an object with the properties:
|
|
342
|
+
* 'msg': an array of one or more messages, if the string is invalid or
|
|
343
|
+
* an error occurred, indicating the problem, or a suggestion of a
|
|
344
|
+
* substitution such as the substitution of 'G' for 'Gauss', or
|
|
345
|
+
* an empty array if no messages were generated. If this is not empty,
|
|
346
|
+
* no other information will be returned.
|
|
347
|
+
* 'magnitude': the new value when fromVal units of fromUnits is expressed in the base units.
|
|
348
|
+
* 'fromUnitIsSpecial': whether the input unit fromUnit is a "special unit"
|
|
349
|
+
* as defined in UCUM. This means there is some function applied to convert
|
|
350
|
+
* between fromUnit and the base units, so the returned magnitude is likely not
|
|
351
|
+
* useful as a scale factor for other conversions (i.e., it only has validity
|
|
352
|
+
* and usefulness for the input values that produced it).
|
|
353
|
+
* 'unitToExp': a map of base units in uStr to their exponent
|
|
354
|
+
*/
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
convertToBaseUnits(fromUnit, fromVal) {
|
|
358
|
+
let inputUnitLookup = this.getSpecifiedUnit(fromUnit, 'validate');
|
|
359
|
+
let retObj = {};
|
|
360
|
+
let unit = inputUnitLookup.unit;
|
|
361
|
+
retObj.msg = inputUnitLookup.retMsg || [];
|
|
362
|
+
|
|
363
|
+
if (!unit) {
|
|
364
|
+
if (inputUnitLookup.retMsg?.length == 0) retObj.msg.push('Could not find unit information for ' + fromUnit);
|
|
365
|
+
} else if (unit.isArbitrary_) {
|
|
366
|
+
retObj.msg.push('Arbitrary units cannot be converted to base units or other units.');
|
|
367
|
+
} else if (retObj.msg.length == 0) {
|
|
368
|
+
let unitToExp = {};
|
|
369
|
+
let dimVec = unit.dim_?.dimVec_;
|
|
370
|
+
let baseUnitString = '1';
|
|
371
|
+
|
|
372
|
+
if (dimVec) {
|
|
373
|
+
let dimVecIndexToBaseUnit = UnitTables.getInstance().dimVecIndexToBaseUnit_;
|
|
374
|
+
|
|
375
|
+
for (let i = 0, len = dimVec.length; i < len; ++i) {
|
|
376
|
+
let exp = dimVec[i];
|
|
377
|
+
|
|
378
|
+
if (exp) {
|
|
379
|
+
unitToExp[dimVecIndexToBaseUnit[i]] = exp;
|
|
380
|
+
baseUnitString += '.' + dimVecIndexToBaseUnit[i] + exp;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
} // The unit might have a conversion function, which has to be applied; we
|
|
384
|
+
// cannot just assume unit_.magnitude_ is the magnitude in base units.
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
let retUnitLookup = this.getSpecifiedUnit(baseUnitString, 'validate'); // There should not be any error in retUnitLookup, unless there is a bug.
|
|
388
|
+
|
|
389
|
+
let retUnit = retUnitLookup.unit;
|
|
390
|
+
if (!retUnit && retUnitLookup.retMsg?.length == 0) retObj.msg.push('Unable construct base unit string; tried ' + baseUnitString);else {
|
|
391
|
+
try {
|
|
392
|
+
retObj.magnitude = retUnit.convertFrom(fromVal, unit);
|
|
393
|
+
} catch (e) {
|
|
394
|
+
retObj.msg.push(e.toString());
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
if (retObj.msg.length == 0) {
|
|
398
|
+
retObj.unitToExp = unitToExp;
|
|
399
|
+
retObj.fromUnitIsSpecial = unit.isSpecial_;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
return retObj;
|
|
405
|
+
}
|
|
336
406
|
/**
|
|
337
407
|
* This method accepts a term and looks for units that include it as
|
|
338
408
|
* a synonym - or that include the term in its name.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../source/ucumLhcUtils.js"],"names":["Ucum","require","UnitTables","UnitString","UcumLhcUtils","constructor","getInstance","unitsCount","ucumJsonDefs","loadJsonDefs","uStrParser_","useHTMLInMessages","use","undefined","useBraceMsgForEachString","validateUnitString","uStr","suggest","valConv","resp","getSpecifiedUnit","theUnit","retObj","csCode_","name_","guidance_","convertUnitTo","fromUnitCode","fromVal","toUnitCode","molecularWeight","returnObj","trim","push","isNaN","intUtils_","isNumericString","fromUnit","parseResp","concat","toUnit","convertFrom","moleExp_","Error","isMoleMassCommensurable","convertMolToMass","convertMassToMol","err","message","needMoleWeightMsg_","checkSynonyms","theSyn","getSynonyms","uName","utab","getUnitByCode","parseString","console","log","unshift","commensurablesList","fromName","retMsg","commUnits","length","dimVec","fromDim","getProperty","getUnitsByD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AAxB;AACA,QAAIA,SAAS,CAAC,QAAD,CAAT,CAAoB0B,MAApB,GAA6B,CAAjC,EACEF,MAAM,GAAGxB,SAAS,CAAC,QAAD,CAAlB;;AACF,QAAI,CAACD,QAAL,EAAe;AACbyB,MAAAA,MAAM,CAAC7B,IAAP,CAAa,uBAAsB4B,QAAS,GAA5C;AACD,KAFD,MAGK;AACH,UAAII,MAAM,GAAG,IAAb;AACA,UAAIC,OAAO,GAAG7B,QAAQ,CAAC8B,WAAT,CAAqB,MAArB,CAAd;;AACA,UAAI,CAACD,OAAL,EAAc;AACZJ,QAAAA,MAAM,CAAC7B,IAAP,CAAY,2CAA2C4B,QAAvD;AACD,OAFD,MAGK;AACH,YAAI;AACFI,UAAAA,MAAM,GAAGC,OAAO,CAACC,WAAR,CAAoB,SAApB,CAAT;AACD,SAFD,CAGA,OAAOpB,GAAP,EAAY;AACVe,UAAAA,MAAM,CAAC7B,IAAP,CAAYc,GAAG,CAACC,OAAhB;AACA,cAAID,GAAG,CAACC,OAAJ,KACF,qDADF,EAEEiB,MAAM,GAAG,IAAT;AACH;;AACD,YAAIA,MAAJ,EAAY;AACV,cAAIX,IAAI,GAAGpD,UAAU,CAACI,WAAX,EAAX;AACAyD,UAAAA,SAAS,GAAGT,IAAI,CAACc,mBAAL,CAAyBH,MAAzB,CAAZ;AACD;AACF,OApBE,CAoBD;;AACH,KAhC0B,CAgCzB;;;AACF,WAAO,CAACF,SAAD,EAAaD,MAAb,CAAP;AACD,GA5duB,CA4dtB;;;AA5dsB,C,CA8dxB;;AAGF;;;;;;;;;;;;;;;;;;AAcA1D,YAAY,CAACE,WAAb,GAA2B,YAAU;AACnC,SAAO,IAAIF,YAAJ,EAAP;AACD,CAFD","sourcesContent":["/**\n * This class provides a single point of access to the LHC UCUM utilities\n *\n * @author Lee Mericle\n *\n */\nvar Ucum = require('./config.js').Ucum;\nimport {ucumJsonDefs} from './ucumJsonDefs.js';\nvar UnitTables = require('./unitTables.js').UnitTables;\nvar UnitString = require('./unitString.js').UnitString;\n\nimport * as intUtils_ from \"./ucumInternalUtils.js\";\n\n/**\n * UCUM external utilities class\n */\nexport class UcumLhcUtils {\n\n /**\n * Constructor. This loads the json prefix and unit definitions if\n * they haven't been loaded already and creates itself as a singleton object.\n *\n */\n constructor() {\n\n if (UnitTables.getInstance().unitsCount() === 0) {\n\n // Load the prefix and unit objects\n ucumJsonDefs.loadJsonDefs();\n }\n\n // Get the UnitString parser that will be used with this instance\n // of the LHC Utilities\n this.uStrParser_ = UnitString.getInstance();\n\n } // end constructor\n\n\n /**\n * This method calls the useHTMLInMessages method on the UnitString\n * object. It should be called by web applications that use\n * these utilities.\n *\n * @param use flag indicating whether or not to use the braces message;\n * defaults to true\n */\n useHTMLInMessages(use) {\n if (use === undefined)\n use = true ;\n this.uStrParser_.useHTMLInMessages(use);\n }\n\n\n /**\n * This method calls the useBraceMsgForEachString method on the UnitString\n * object. It should be called by web applications where unit\n * strings are validated individually (as opposed to validating a whole\n * file of unit strings).\n *\n * @param use flag indicating whether or not to use the braces message;\n * defaults to true\n */\n useBraceMsgForEachString(use) {\n if (use === undefined)\n use = true ;\n this.uStrParser_.useBraceMsgForEachString(use);\n }\n\n\n /**\n * This method validates a unit string. It first checks to see if the\n * string passed in is a unit code that is found in the unit codes table.\n * If it is not found it parses the string to see if it resolves to a\n * valid unit string.\n *\n * If a valid unit cannot be found, the string is tested for some common\n * errors, such as missing brackets or a missing multiplication operator.\n * If found, the error is reported in the messages array that is returned.\n *\n * If a valid unit cannot be found and an error cannot be discerned, this\n * may return, if requested, a list of suggested units in the messages\n * array that is returned. Suggestions are based on matching the expression\n * with unit names and synonyms.\n *\n * @param uStr the string to be validated\n * @param suggest a boolean to indicate whether or not suggestions are\n * requested for a string that cannot be resolved to a valid unit;\n * true indicates suggestions are wanted; false indicates they are not,\n * and is the default if the parameter is not specified;\n * @param valConv a string indicating if this validation request was initiated\n * by a validation task ('validate') or a conversion task ('convert'),\n * used only for the demo code, and the default is 'Validator' if the\n * parameter is not specified;\n * @returns an object with five properties:\n * 'status' will be 'valid' (the uStr is a valid UCUM code), 'invalid'\n * (the uStr is not a valid UCUM code, and substitutions or\n * suggestions may or may not be returned, depending on what was\n * requested and found); or 'error' (an input or programming error\n * occurred);\n * 'ucumCode' the valid ucum code, which may differ from what was passed\n * in (e.g., if 'Gauss' is passed in, this will contain 'G') OR null if\n * the string was flagged as invalid or an error occurred;\n * 'msg' is an array of one or more messages, if the string is invalid or\n * an error occurred, indicating the problem, or an explanation of a\n * substitution such as the substitution of 'G' for 'Gauss', or\n * an empty array if no messages were generated;\n * 'unit' which is null if no unit is found, or a hash for a unit found:\n * 'code' is the unit's ucum code (G in the above example;\n * 'name' is the unit's name (Gauss in the above example); and\n * 'guidance' is the unit's guidance/description data; and\n * 'suggestions' if suggestions were requested and found, this is an array\n * of one or more hash objects. Each hash contains three elements:\n * 'msg' which is a message indicating what part of the uStr input\n * parameter the suggestions are for;\n * 'invalidUnit' which is the unit expression the suggestions are\n * for; and\n * 'units' which is an array of data for each suggested unit found.\n * Each array will contain the unit code, the unit name and the\n * unit guidance (if any).\n * If no suggestions were requested and found, this property is not\n * returned.\n */\n validateUnitString(uStr, suggest, valConv) {\n\n if (suggest === undefined)\n suggest = false ;\n\n if (valConv === undefined)\n valConv = 'validate' ;\n\n let resp = this.getSpecifiedUnit(uStr, valConv, suggest);\n let theUnit = resp['unit'];\n let retObj = {};\n if (!theUnit) {\n retObj = {'status': (!resp['origString'] || resp['origString'] === null) ?\n 'error' : 'invalid',\n 'ucumCode': null};\n }\n else {\n retObj = {'status': resp['origString'] === uStr ? 'valid': 'invalid',\n 'ucumCode': resp['origString'],\n 'unit': {'code': theUnit.csCode_,\n 'name': theUnit.name_,\n 'guidance': theUnit.guidance_ }};\n }\n if (resp['suggestions']) {\n retObj['suggestions'] = resp['suggestions'];\n }\n retObj['msg'] = resp['retMsg'];\n return retObj;\n\n } // end validateUnitString\n\n\n /**\n * This method converts one unit to another\n *\n * @param fromUnitCode the unit code/expression/string of the unit to be converted\n * @param fromVal the number of \"from\" units to be converted to \"to\" units\n * @param toUnitCode the unit code/expression/string of the unit that the from\n * field is to be converted to\n * @param suggest a boolean to indicate whether or not suggestions are\n * requested for a string that cannot be resolved to a valid unit;\n * true indicates suggestions are wanted; false indicates they are not,\n * and is the default if the parameter is not specified;\n * @param molecularWeight the molecular weight of the substance in question\n * when a conversion is being requested from mass to moles and vice versa.\n * This is required when one of the units represents a value in moles. It is\n * ignored if neither unit includes a measurement in moles.\n * @returns a hash with six elements:\n * 'status' that will be: 'succeeded' if the conversion was successfully\n * calculated; 'failed' if the conversion could not be made, e.g., if\n * the units are not commensurable; or 'error' if an error occurred;\n * 'toVal' the numeric value indicating the conversion amount, or null\n * if the conversion failed (e.g., if the units are not commensurable);\n * 'msg' is an array message, if the string is invalid or an error occurred,\n * indicating the problem, or an explanation of a substitution such as\n * the substitution of 'G' for 'Gauss', or an empty array if no\n * messages were generated;\n * 'suggestions' if suggestions were requested and found, this is a hash\n * that contains at most two elements:\n * 'from' which, if the fromUnitCode input parameter or one or more of\n * its components could not be found, is an array one or more hash\n * objects. Each hash contains three elements:\n * 'msg' which is a message indicating what unit expression the\n * suggestions are for;\n * 'invalidUnit' which is the unit expression the suggestions\n * are for; and\n * 'units' which is an array of data for each suggested unit found.\n * Each array will contain the unit code, the unit name and the\n * unit guidance (if any).\n * If no suggestions were found for the fromUnitCode this element\n * will not be included.\n * 'to' which, if the \"to\" unit expression or one or more of its\n * components could not be found, is an array one or more hash objects. Each hash\n * contains three elements:\n * 'msg' which is a message indicating what toUnitCode input\n * parameter the suggestions are for;\n * 'invalidUnit' which is the unit expression the suggestions\n * are for; and\n * 'units' which is an array of data for each suggested unit found.\n * Each array will contain the unit code, the unit name and the\n * unit guidance (if any).\n * If no suggestions were found for the toUnitCode this element\n * will not be included.\n * No 'suggestions' element will be included in the returned hash\n * object if none were found, whether or not they were requested.\n * 'fromUnit' the unit object for the fromUnitCode passed in; returned\n * in case it's needed for additional data from the object; and\n * 'toUnit' the unit object for the toUnitCode passed in; returned\n * in case it's needed for additional data from the object.\n */\n convertUnitTo(fromUnitCode, fromVal, toUnitCode, suggest, molecularWeight) {\n if (suggest === undefined)\n suggest = false ;\n\n if (molecularWeight === undefined)\n molecularWeight = null ;\n\n let returnObj = {'status' : 'failed',\n 'toVal' : null,\n 'msg' : []} ;\n\n if (fromUnitCode) {\n fromUnitCode = fromUnitCode.trim();\n }\n if (!fromUnitCode || fromUnitCode == '') {\n returnObj['status'] = 'error';\n returnObj['msg'].push('No \"from\" unit expression specified.');\n }\n if (fromVal === null || isNaN(fromVal) || (typeof fromVal !== 'number' &&\n !intUtils_.isNumericString(fromVal))) {\n returnObj['status'] = 'error';\n returnObj['msg'].push('No \"from\" value, or an invalid \"from\" value, ' +\n 'was specified.');\n }\n if (toUnitCode) {\n toUnitCode = toUnitCode.trim();\n }\n if (!toUnitCode || toUnitCode == '') {\n returnObj['status'] = 'error';\n returnObj['msg'].push('No \"to\" unit expression specified.');\n }\n if (returnObj['status'] !== 'error') {\n try {\n let fromUnit = null;\n\n let parseResp = this.getSpecifiedUnit(fromUnitCode, 'convert', suggest);\n fromUnit = parseResp['unit'];\n if (parseResp['retMsg'])\n returnObj['msg'] = returnObj['msg'].concat(parseResp['retMsg']);\n if (parseResp['suggestions']) {\n returnObj['suggestions'] = {};\n returnObj['suggestions']['from'] = parseResp['suggestions'];\n }\n if (!fromUnit) {\n returnObj['msg'].push(`Unable to find a unit for ${fromUnitCode}, ` +\n `so no conversion could be performed.`);\n }\n\n let toUnit = null;\n parseResp = this.getSpecifiedUnit(toUnitCode, 'convert', suggest);\n toUnit = parseResp['unit'];\n if (parseResp['retMsg'])\n returnObj['msg'] = returnObj['msg'].concat(parseResp['retMsg']);\n if (parseResp['suggestions']) {\n if (!returnObj['suggestions'])\n returnObj['suggestions'] = {} ;\n returnObj['suggestions']['to'] = parseResp['suggestions'];\n }\n if (!toUnit) {\n returnObj['msg'].push(`Unable to find a unit for ${toUnitCode}, ` +\n `so no conversion could be performed.`);\n }\n\n if (fromUnit && toUnit) {\n try {\n // if no molecular weight was specified perform a normal conversion\n if (!molecularWeight) {\n returnObj['toVal'] = toUnit.convertFrom(fromVal, fromUnit);\n }\n else {\n if (fromUnit.moleExp_ !== 0 && toUnit.moleExp_ !== 0) {\n throw(new Error('A molecular weight was specified ' +\n 'but a mass <-> mole conversion cannot be executed for two ' +\n 'mole-based units. No conversion was attempted.'));\n }\n if (fromUnit.moleExp_ === 0 && toUnit.moleExp_ === 0) {\n throw(new Error('A molecular weight was specified ' +\n 'but a mass <-> mole conversion cannot be executed when ' +\n 'neither unit is mole-based. No conversion was attempted.'));\n }\n if (!fromUnit.isMoleMassCommensurable(toUnit)) {\n throw(new Error(`Sorry. ${fromUnitCode} cannot be ` +\n `converted to ${toUnitCode}.`));\n }\n\n // if the \"from\" unit is a mole-based unit, assume a mole to mass\n // request\n if (fromUnit.moleExp_ !== 0) {\n returnObj['toVal'] =\n fromUnit.convertMolToMass(fromVal, toUnit, molecularWeight);\n }\n // else the \"to\" unit must be the mole-based unit, so assume a\n // mass to mole request\n else {\n returnObj['toVal'] =\n fromUnit.convertMassToMol(fromVal, toUnit, molecularWeight);\n }\n } // end if a molecular weight was specified\n\n // if an error hasn't been thrown - either from convertFrom or here,\n // set the return object to show success\n returnObj['status'] = 'succeeded';\n returnObj['fromUnit'] = fromUnit;\n returnObj['toUnit'] = toUnit;\n }\n catch (err) {\n returnObj['status'] = 'failed';\n returnObj['msg'].push(err.message);\n }\n\n\n } // end if we have the from and to units\n }\n catch (err) {\n if (err.message == Ucum.needMoleWeightMsg_)\n returnObj['status'] = 'failed';\n else\n returnObj['status'] = 'error';\n returnObj['msg'].push(err.message);\n }\n }\n\n return returnObj ;\n\n } // end convertUnitTo\n\n\n /**\n * This method accepts a term and looks for units that include it as\n * a synonym - or that include the term in its name.\n *\n * @param theSyn the term to search for\n * @returns a hash with up to three elements:\n * 'status' contains the status of the request, which can be 'error',\n * 'failed' or succeeded';\n * 'msg' which contains a message for an error or if no units were found; and\n * 'units' which is an array that contains one hash for each unit found:\n * 'code' is the unit's csCode_\n * 'name' is the unit's name_\n * 'guidance' is the unit's guidance_\n *\n */\n checkSynonyms(theSyn) {\n let retObj = {} ;\n if (theSyn === undefined || theSyn === null) {\n retObj['status'] = 'error';\n retObj['msg'] = 'No term specified for synonym search.'\n }\n else {\n retObj = intUtils_.getSynonyms(theSyn);\n } // end if a search synonym was supplied\n\n return retObj ;\n\n } // end checkSynonyms\n\n\n /**\n * This method parses a unit string to get (or try to get) the unit\n * represented by the string. It returns an error message if no string was specified\n * or if any errors were encountered trying to get the unit.\n *\n * @param uName the expression/string representing the unit\n * @param valConv indicates what type of request this is for - a request to\n * validate (pass in 'validate') or a request to convert (pass in 'convert')\n * @param suggest a boolean to indicate whether or not suggestions are\n * requested for a string that cannot be resolved to a valid unit;\n * true indicates suggestions are wanted; false indicates they are not,\n * and is the default if the parameter is not specified;\n * @returns a hash containing:\n * 'unit' the unit object (or null if there were problems creating the\n * unit);\n * 'origString' the possibly updated unit string passed in;\n * 'retMsg' an array of user messages (informational, error or warning) if\n * any were generated (IF any were generated, otherwise will be an\n * empty array); and\n * 'suggestions' is an array of 1 or more hash objects. Each hash\n * contains three elements:\n * 'msg' which is a message indicating what unit expression the\n * suggestions are for;\n * 'invalidUnit' which is the unit expression the suggestions are\n * for; and\n * 'units' which is an array of data for each suggested unit found.\n * Each array will contain the unit code, the unit name and the\n * unit guidance (if any).\n * The return hash will not contain a suggestions array if a valid unit\n * was found or if suggestions were not requested and found.\n */\n getSpecifiedUnit(uName, valConv, suggest) {\n\n if (suggest === undefined)\n suggest = false ;\n\n let retObj = {};\n retObj['retMsg'] = [];\n\n if (!uName) {\n retObj['retMsg'].push('No unit string specified.');\n }\n else {\n let utab = UnitTables.getInstance();\n uName = uName.trim();\n\n // go ahead and just try using the name as the code. This may or may not\n // work, but if it does, it cuts out a lot of parsing.\n let theUnit = utab.getUnitByCode(uName);\n\n // If we found it, set the returned unit string to what was passed in;\n // otherwise try parsing as a unit string\n if (theUnit) {\n retObj['unit'] = theUnit ;\n retObj['origString'] = uName;\n }\n else {\n try {\n let resp = this.uStrParser_.parseString(uName, valConv, suggest);\n retObj['unit'] = resp[0];\n retObj['origString'] = resp[1];\n if (resp[2])\n retObj['retMsg'] = resp[2];\n retObj['suggestions'] = resp[3];\n }\n catch (err) {\n console.log(`Unit requested for unit string ${uName}.` +\n 'request unsuccessful; error thrown = ' + err.message);\n retObj['retMsg'].unshift(`${uName} is not a valid unit. ` +\n `${err.message}`);\n }\n } // end if the unit was not found as a unit name\n } // end if a unit expression was specified\n\n return retObj;\n\n } // end getSpecifiedUnit\n\n\n /**\n * This method retrieves a list of units commensurable, i.e., that can be\n * converted from and to, a specified unit. Returns an error if the \"from\"\n * unit cannot be found.\n *\n * @param fromName the name/unit string of the \"from\" unit\n * @returns an array containing two elements;\n * first element is the list of commensurable units if any were found\n * second element is an error message if the \"from\" unit is not found\n */\n commensurablesList(fromName) {\n\n let retMsg = [];\n let commUnits = null ;\n let parseResp = this.getSpecifiedUnit(fromName, 'validate', false);\n let fromUnit = parseResp['unit'];\n if (parseResp['retMsg'].length > 0)\n retMsg = parseResp['retMsg'] ;\n if (!fromUnit) {\n retMsg.push(`Could not find unit ${fromName}.`);\n }\n else {\n let dimVec = null ;\n let fromDim = fromUnit.getProperty('dim_');\n if (!fromDim) {\n retMsg.push('No commensurable units were found for ' + fromName) ;\n }\n else {\n try {\n dimVec = fromDim.getProperty('dimVec_');\n }\n catch (err) {\n retMsg.push(err.message);\n if (err.message ===\n \"Dimension does not have requested property(dimVec_)\")\n dimVec = null;\n }\n if (dimVec) {\n let utab = UnitTables.getInstance();\n commUnits = utab.getUnitsByDimension(dimVec);\n }\n } // end if the from unit has a dimension vector\n } // end if we found a \"from\" unit\n return [commUnits , retMsg];\n } // end commensurablesList\n\n} // end UcumLhcUtils class\n\n\n/**\n * This function exists ONLY until the original UcumLhcUtils constructor\n * is called for the first time. It's defined here in case getInstance\n * is called before the constructor. This calls the constructor.\n *\n * The constructor redefines the getInstance function to return the\n * singleton UcumLhcUtils object. This is based on the UnitTables singleton\n * implementation; see more detail in the UnitTables constructor description.\n *\n * NO LONGER TRUE - not implemented as a singleton. This method retained to\n * avoid problems with calls to it that exist throughout the code.\n *\n * @return the (formerly singleton) UcumLhcUtils object.\n */\nUcumLhcUtils.getInstance = function(){\n return new UcumLhcUtils();\n} ;\n\n\n\n\n"],"file":"ucumLhcUtils.js"}
|
|
1
|
+
{"version":3,"sources":["../source/ucumLhcUtils.js"],"names":["Ucum","require","UnitTables","UnitString","UcumLhcUtils","constructor","getInstance","unitsCount","ucumJsonDefs","loadJsonDefs","uStrParser_","useHTMLInMessages","use","undefined","useBraceMsgForEachString","validateUnitString","uStr","suggest","valConv","resp","getSpecifiedUnit","theUnit","retObj","csCode_","name_","guidance_","convertUnitTo","fromUnitCode","fromVal","toUnitCode","molecularWeight","returnObj","trim","push","isNaN","intUtils_","isNumericString","fromUnit","parseResp","concat","toUnit","convertFrom","moleExp_","Error","isMoleMassCommensurable","convertMolToMass","convertMassToMol","err","message","needMoleWeightMsg_","convertToBaseUnits","inputUnitLookup","unit","msg","retMsg","length","isArbitrary_","unitToExp","dimVec","dim_","dimVec_","baseUnitString","dimVecIndexToBaseUnit","dimVecIndexToBaseUnit_","i","len","exp","retUnitLookup","retUnit","magnitude","e","toString","fromUnitIsSpecial","isSpecial_","checkSynonyms","theSyn","getSynonyms","uName","utab","getUnitByCode","parseString","console","log","unshift","commensurablesList","fromName","commUnits","fromDim","getProperty","getUnitsByDimension"],"mappings":";;;;;;;AAOA;;AAIA;;;;;;AAXA;;;;;;AAMA,IAAIA,IAAI,GAAGC,OAAO,CAAC,aAAD,CAAP,CAAuBD,IAAlC;;AAEA,IAAIE,UAAU,GAAGD,OAAO,CAAC,iBAAD,CAAP,CAA2BC,UAA5C;;AACA,IAAIC,UAAU,GAAGF,OAAO,CAAC,iBAAD,CAAP,C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,GAAG,IAAT;AACH;;AACD,YAAIA,MAAJ,EAAY;AACV,cAAIoB,IAAI,GAAG5E,UAAU,CAACI,WAAX,EAAX;AACAgF,UAAAA,SAAS,GAAGR,IAAI,CAACW,mBAAL,CAAyB/B,MAAzB,CAAZ;AACD;AACF,OApBE,CAoBD;;AACH,KAhC0B,CAgCzB;;;AACF,WAAO,CAAC4B,SAAD,EAAahC,MAAb,CAAP;AACD,GAliBuB,CAkiBtB;;;AAliBsB,C,CAoiBxB;;AAGF;;;;;;;;;;;;;;;;;;AAcAlD,YAAY,CAACE,WAAb,GAA2B,YAAU;AACnC,SAAO,IAAIF,YAAJ,EAAP;AACD,CAFD","sourcesContent":["/**\n * This class provides a single point of access to the LHC UCUM utilities\n *\n * @author Lee Mericle\n *\n */\nvar Ucum = require('./config.js').Ucum;\nimport {ucumJsonDefs} from './ucumJsonDefs.js';\nvar UnitTables = require('./unitTables.js').UnitTables;\nvar UnitString = require('./unitString.js').UnitString;\n\nimport * as intUtils_ from \"./ucumInternalUtils.js\";\n\n/**\n * UCUM external utilities class\n */\nexport class UcumLhcUtils {\n\n /**\n * Constructor. This loads the json prefix and unit definitions if\n * they haven't been loaded already and creates itself as a singleton object.\n *\n */\n constructor() {\n\n if (UnitTables.getInstance().unitsCount() === 0) {\n\n // Load the prefix and unit objects\n ucumJsonDefs.loadJsonDefs();\n }\n\n // Get the UnitString parser that will be used with this instance\n // of the LHC Utilities\n this.uStrParser_ = UnitString.getInstance();\n\n } // end constructor\n\n\n /**\n * This method calls the useHTMLInMessages method on the UnitString\n * object. It should be called by web applications that use\n * these utilities.\n *\n * @param use flag indicating whether or not to use the braces message;\n * defaults to true\n */\n useHTMLInMessages(use) {\n if (use === undefined)\n use = true ;\n this.uStrParser_.useHTMLInMessages(use);\n }\n\n\n /**\n * This method calls the useBraceMsgForEachString method on the UnitString\n * object. It should be called by web applications where unit\n * strings are validated individually (as opposed to validating a whole\n * file of unit strings).\n *\n * @param use flag indicating whether or not to use the braces message;\n * defaults to true\n */\n useBraceMsgForEachString(use) {\n if (use === undefined)\n use = true ;\n this.uStrParser_.useBraceMsgForEachString(use);\n }\n\n\n /**\n * This method validates a unit string. It first checks to see if the\n * string passed in is a unit code that is found in the unit codes table.\n * If it is not found it parses the string to see if it resolves to a\n * valid unit string.\n *\n * If a valid unit cannot be found, the string is tested for some common\n * errors, such as missing brackets or a missing multiplication operator.\n * If found, the error is reported in the messages array that is returned.\n *\n * If a valid unit cannot be found and an error cannot be discerned, this\n * may return, if requested, a list of suggested units in the messages\n * array that is returned. Suggestions are based on matching the expression\n * with unit names and synonyms.\n *\n * @param uStr the string to be validated\n * @param suggest a boolean to indicate whether or not suggestions are\n * requested for a string that cannot be resolved to a valid unit;\n * true indicates suggestions are wanted; false indicates they are not,\n * and is the default if the parameter is not specified;\n * @param valConv a string indicating if this validation request was initiated\n * by a validation task ('validate') or a conversion task ('convert'),\n * used only for the demo code, and the default is 'Validator' if the\n * parameter is not specified;\n * @returns an object with five properties:\n * 'status' will be 'valid' (the uStr is a valid UCUM code), 'invalid'\n * (the uStr is not a valid UCUM code, and substitutions or\n * suggestions may or may not be returned, depending on what was\n * requested and found); or 'error' (an input or programming error\n * occurred);\n * 'ucumCode' the valid ucum code, which may differ from what was passed\n * in (e.g., if 'Gauss' is passed in, this will contain 'G') OR null if\n * the string was flagged as invalid or an error occurred;\n * 'msg' is an array of one or more messages, if the string is invalid or\n * an error occurred, indicating the problem, or an explanation of a\n * substitution such as the substitution of 'G' for 'Gauss', or\n * an empty array if no messages were generated;\n * 'unit' which is null if no unit is found, or a hash for a unit found:\n * 'code' is the unit's ucum code (G in the above example;\n * 'name' is the unit's name (Gauss in the above example); and\n * 'guidance' is the unit's guidance/description data; and\n * 'suggestions' if suggestions were requested and found, this is an array\n * of one or more hash objects. Each hash contains three elements:\n * 'msg' which is a message indicating what part of the uStr input\n * parameter the suggestions are for;\n * 'invalidUnit' which is the unit expression the suggestions are\n * for; and\n * 'units' which is an array of data for each suggested unit found.\n * Each array will contain the unit code, the unit name and the\n * unit guidance (if any).\n * If no suggestions were requested and found, this property is not\n * returned.\n */\n validateUnitString(uStr, suggest, valConv) {\n\n if (suggest === undefined)\n suggest = false ;\n\n if (valConv === undefined)\n valConv = 'validate' ;\n\n let resp = this.getSpecifiedUnit(uStr, valConv, suggest);\n let theUnit = resp['unit'];\n let retObj = {};\n if (!theUnit) {\n retObj = {'status': (!resp['origString'] || resp['origString'] === null) ?\n 'error' : 'invalid',\n 'ucumCode': null};\n }\n else {\n retObj = {'status': resp['origString'] === uStr ? 'valid': 'invalid',\n 'ucumCode': resp['origString'],\n 'unit': {'code': theUnit.csCode_,\n 'name': theUnit.name_,\n 'guidance': theUnit.guidance_ }};\n }\n if (resp['suggestions']) {\n retObj['suggestions'] = resp['suggestions'];\n }\n retObj['msg'] = resp['retMsg'];\n return retObj;\n\n } // end validateUnitString\n\n\n /**\n * This method converts one unit to another\n *\n * @param fromUnitCode the unit code/expression/string of the unit to be converted\n * @param fromVal the number of \"from\" units to be converted to \"to\" units\n * @param toUnitCode the unit code/expression/string of the unit that the from\n * field is to be converted to\n * @param suggest a boolean to indicate whether or not suggestions are\n * requested for a string that cannot be resolved to a valid unit;\n * true indicates suggestions are wanted; false indicates they are not,\n * and is the default if the parameter is not specified;\n * @param molecularWeight the molecular weight of the substance in question\n * when a conversion is being requested from mass to moles and vice versa.\n * This is required when one of the units represents a value in moles. It is\n * ignored if neither unit includes a measurement in moles.\n * @returns a hash with six elements:\n * 'status' that will be: 'succeeded' if the conversion was successfully\n * calculated; 'failed' if the conversion could not be made, e.g., if\n * the units are not commensurable; or 'error' if an error occurred;\n * 'toVal' the numeric value indicating the conversion amount, or null\n * if the conversion failed (e.g., if the units are not commensurable);\n * 'msg' is an array message, if the string is invalid or an error occurred,\n * indicating the problem, or an explanation of a substitution such as\n * the substitution of 'G' for 'Gauss', or an empty array if no\n * messages were generated;\n * 'suggestions' if suggestions were requested and found, this is a hash\n * that contains at most two elements:\n * 'from' which, if the fromUnitCode input parameter or one or more of\n * its components could not be found, is an array one or more hash\n * objects. Each hash contains three elements:\n * 'msg' which is a message indicating what unit expression the\n * suggestions are for;\n * 'invalidUnit' which is the unit expression the suggestions\n * are for; and\n * 'units' which is an array of data for each suggested unit found.\n * Each array will contain the unit code, the unit name and the\n * unit guidance (if any).\n * If no suggestions were found for the fromUnitCode this element\n * will not be included.\n * 'to' which, if the \"to\" unit expression or one or more of its\n * components could not be found, is an array one or more hash objects. Each hash\n * contains three elements:\n * 'msg' which is a message indicating what toUnitCode input\n * parameter the suggestions are for;\n * 'invalidUnit' which is the unit expression the suggestions\n * are for; and\n * 'units' which is an array of data for each suggested unit found.\n * Each array will contain the unit code, the unit name and the\n * unit guidance (if any).\n * If no suggestions were found for the toUnitCode this element\n * will not be included.\n * No 'suggestions' element will be included in the returned hash\n * object if none were found, whether or not they were requested.\n * 'fromUnit' the unit object for the fromUnitCode passed in; returned\n * in case it's needed for additional data from the object; and\n * 'toUnit' the unit object for the toUnitCode passed in; returned\n * in case it's needed for additional data from the object.\n */\n convertUnitTo(fromUnitCode, fromVal, toUnitCode, suggest, molecularWeight) {\n if (suggest === undefined)\n suggest = false ;\n\n if (molecularWeight === undefined)\n molecularWeight = null ;\n\n let returnObj = {'status' : 'failed',\n 'toVal' : null,\n 'msg' : []} ;\n\n if (fromUnitCode) {\n fromUnitCode = fromUnitCode.trim();\n }\n if (!fromUnitCode || fromUnitCode == '') {\n returnObj['status'] = 'error';\n returnObj['msg'].push('No \"from\" unit expression specified.');\n }\n if (fromVal === null || isNaN(fromVal) || (typeof fromVal !== 'number' &&\n !intUtils_.isNumericString(fromVal))) {\n returnObj['status'] = 'error';\n returnObj['msg'].push('No \"from\" value, or an invalid \"from\" value, ' +\n 'was specified.');\n }\n if (toUnitCode) {\n toUnitCode = toUnitCode.trim();\n }\n if (!toUnitCode || toUnitCode == '') {\n returnObj['status'] = 'error';\n returnObj['msg'].push('No \"to\" unit expression specified.');\n }\n if (returnObj['status'] !== 'error') {\n try {\n let fromUnit = null;\n\n let parseResp = this.getSpecifiedUnit(fromUnitCode, 'convert', suggest);\n fromUnit = parseResp['unit'];\n if (parseResp['retMsg'])\n returnObj['msg'] = returnObj['msg'].concat(parseResp['retMsg']);\n if (parseResp['suggestions']) {\n returnObj['suggestions'] = {};\n returnObj['suggestions']['from'] = parseResp['suggestions'];\n }\n if (!fromUnit) {\n returnObj['msg'].push(`Unable to find a unit for ${fromUnitCode}, ` +\n `so no conversion could be performed.`);\n }\n\n let toUnit = null;\n parseResp = this.getSpecifiedUnit(toUnitCode, 'convert', suggest);\n toUnit = parseResp['unit'];\n if (parseResp['retMsg'])\n returnObj['msg'] = returnObj['msg'].concat(parseResp['retMsg']);\n if (parseResp['suggestions']) {\n if (!returnObj['suggestions'])\n returnObj['suggestions'] = {} ;\n returnObj['suggestions']['to'] = parseResp['suggestions'];\n }\n if (!toUnit) {\n returnObj['msg'].push(`Unable to find a unit for ${toUnitCode}, ` +\n `so no conversion could be performed.`);\n }\n\n if (fromUnit && toUnit) {\n try {\n // if no molecular weight was specified perform a normal conversion\n if (!molecularWeight) {\n returnObj['toVal'] = toUnit.convertFrom(fromVal, fromUnit);\n }\n else {\n if (fromUnit.moleExp_ !== 0 && toUnit.moleExp_ !== 0) {\n throw(new Error('A molecular weight was specified ' +\n 'but a mass <-> mole conversion cannot be executed for two ' +\n 'mole-based units. No conversion was attempted.'));\n }\n if (fromUnit.moleExp_ === 0 && toUnit.moleExp_ === 0) {\n throw(new Error('A molecular weight was specified ' +\n 'but a mass <-> mole conversion cannot be executed when ' +\n 'neither unit is mole-based. No conversion was attempted.'));\n }\n if (!fromUnit.isMoleMassCommensurable(toUnit)) {\n throw(new Error(`Sorry. ${fromUnitCode} cannot be ` +\n `converted to ${toUnitCode}.`));\n }\n\n // if the \"from\" unit is a mole-based unit, assume a mole to mass\n // request\n if (fromUnit.moleExp_ !== 0) {\n returnObj['toVal'] =\n fromUnit.convertMolToMass(fromVal, toUnit, molecularWeight);\n }\n // else the \"to\" unit must be the mole-based unit, so assume a\n // mass to mole request\n else {\n returnObj['toVal'] =\n fromUnit.convertMassToMol(fromVal, toUnit, molecularWeight);\n }\n } // end if a molecular weight was specified\n\n // if an error hasn't been thrown - either from convertFrom or here,\n // set the return object to show success\n returnObj['status'] = 'succeeded';\n returnObj['fromUnit'] = fromUnit;\n returnObj['toUnit'] = toUnit;\n }\n catch (err) {\n returnObj['status'] = 'failed';\n returnObj['msg'].push(err.message);\n }\n\n\n } // end if we have the from and to units\n }\n catch (err) {\n if (err.message == Ucum.needMoleWeightMsg_)\n returnObj['status'] = 'failed';\n else\n returnObj['status'] = 'error';\n returnObj['msg'].push(err.message);\n }\n }\n\n return returnObj ;\n\n } // end convertUnitTo\n\n\n /**\n * Converts the given unit string into its base units, their exponents, and\n * a magnitude, and returns that data.\n * @param fromUnit the unit string to be converted to base units information\n * @param fromVal the number of \"from\" units to be converted\n * @returns an object with the properties:\n * 'msg': an array of one or more messages, if the string is invalid or\n * an error occurred, indicating the problem, or a suggestion of a\n * substitution such as the substitution of 'G' for 'Gauss', or\n * an empty array if no messages were generated. If this is not empty,\n * no other information will be returned.\n * 'magnitude': the new value when fromVal units of fromUnits is expressed in the base units.\n * 'fromUnitIsSpecial': whether the input unit fromUnit is a \"special unit\"\n * as defined in UCUM. This means there is some function applied to convert\n * between fromUnit and the base units, so the returned magnitude is likely not\n * useful as a scale factor for other conversions (i.e., it only has validity\n * and usefulness for the input values that produced it).\n * 'unitToExp': a map of base units in uStr to their exponent\n */\n convertToBaseUnits(fromUnit, fromVal) {\n let inputUnitLookup = this.getSpecifiedUnit(fromUnit, 'validate');\n let retObj = {};\n let unit = inputUnitLookup.unit;\n retObj.msg = inputUnitLookup.retMsg || [];\n if (!unit) {\n if (inputUnitLookup.retMsg?.length == 0)\n retObj.msg.push('Could not find unit information for '+fromUnit);\n }\n else if (unit.isArbitrary_) {\n retObj.msg.push('Arbitrary units cannot be converted to base units or other units.');\n }\n else if (retObj.msg.length == 0) {\n let unitToExp = {};\n let dimVec = unit.dim_?.dimVec_\n let baseUnitString = '1';\n if (dimVec) {\n let dimVecIndexToBaseUnit = UnitTables.getInstance().dimVecIndexToBaseUnit_;\n for (let i=0, len=dimVec.length; i<len; ++i) {\n let exp = dimVec[i];\n if (exp) {\n unitToExp[dimVecIndexToBaseUnit[i]] = exp;\n baseUnitString += '.' + dimVecIndexToBaseUnit[i] + exp;\n }\n }\n }\n\n // The unit might have a conversion function, which has to be applied; we\n // cannot just assume unit_.magnitude_ is the magnitude in base units.\n let retUnitLookup = this.getSpecifiedUnit(baseUnitString, 'validate');\n // There should not be any error in retUnitLookup, unless there is a bug.\n let retUnit = retUnitLookup.unit;\n if (!retUnit && retUnitLookup.retMsg?.length == 0)\n retObj.msg.push('Unable construct base unit string; tried '+baseUnitString);\n else {\n try {\n retObj.magnitude = retUnit.convertFrom(fromVal, unit);\n }\n catch (e) {\n retObj.msg.push(e.toString());\n }\n if (retObj.msg.length == 0) {\n retObj.unitToExp = unitToExp;\n retObj.fromUnitIsSpecial = unit.isSpecial_;\n }\n }\n }\n return retObj;\n }\n\n\n /**\n * This method accepts a term and looks for units that include it as\n * a synonym - or that include the term in its name.\n *\n * @param theSyn the term to search for\n * @returns a hash with up to three elements:\n * 'status' contains the status of the request, which can be 'error',\n * 'failed' or succeeded';\n * 'msg' which contains a message for an error or if no units were found; and\n * 'units' which is an array that contains one hash for each unit found:\n * 'code' is the unit's csCode_\n * 'name' is the unit's name_\n * 'guidance' is the unit's guidance_\n *\n */\n checkSynonyms(theSyn) {\n let retObj = {} ;\n if (theSyn === undefined || theSyn === null) {\n retObj['status'] = 'error';\n retObj['msg'] = 'No term specified for synonym search.'\n }\n else {\n retObj = intUtils_.getSynonyms(theSyn);\n } // end if a search synonym was supplied\n\n return retObj ;\n\n } // end checkSynonyms\n\n\n /**\n * This method parses a unit string to get (or try to get) the unit\n * represented by the string. It returns an error message if no string was specified\n * or if any errors were encountered trying to get the unit.\n *\n * @param uName the expression/string representing the unit\n * @param valConv indicates what type of request this is for - a request to\n * validate (pass in 'validate') or a request to convert (pass in 'convert')\n * @param suggest a boolean to indicate whether or not suggestions are\n * requested for a string that cannot be resolved to a valid unit;\n * true indicates suggestions are wanted; false indicates they are not,\n * and is the default if the parameter is not specified;\n * @returns a hash containing:\n * 'unit' the unit object (or null if there were problems creating the\n * unit);\n * 'origString' the possibly updated unit string passed in;\n * 'retMsg' an array of user messages (informational, error or warning) if\n * any were generated (IF any were generated, otherwise will be an\n * empty array); and\n * 'suggestions' is an array of 1 or more hash objects. Each hash\n * contains three elements:\n * 'msg' which is a message indicating what unit expression the\n * suggestions are for;\n * 'invalidUnit' which is the unit expression the suggestions are\n * for; and\n * 'units' which is an array of data for each suggested unit found.\n * Each array will contain the unit code, the unit name and the\n * unit guidance (if any).\n * The return hash will not contain a suggestions array if a valid unit\n * was found or if suggestions were not requested and found.\n */\n getSpecifiedUnit(uName, valConv, suggest) {\n\n if (suggest === undefined)\n suggest = false ;\n\n let retObj = {};\n retObj['retMsg'] = [];\n\n if (!uName) {\n retObj['retMsg'].push('No unit string specified.');\n }\n else {\n let utab = UnitTables.getInstance();\n uName = uName.trim();\n\n // go ahead and just try using the name as the code. This may or may not\n // work, but if it does, it cuts out a lot of parsing.\n let theUnit = utab.getUnitByCode(uName);\n\n // If we found it, set the returned unit string to what was passed in;\n // otherwise try parsing as a unit string\n if (theUnit) {\n retObj['unit'] = theUnit ;\n retObj['origString'] = uName;\n }\n else {\n try {\n let resp = this.uStrParser_.parseString(uName, valConv, suggest);\n retObj['unit'] = resp[0];\n retObj['origString'] = resp[1];\n if (resp[2])\n retObj['retMsg'] = resp[2];\n retObj['suggestions'] = resp[3];\n }\n catch (err) {\n console.log(`Unit requested for unit string ${uName}.` +\n 'request unsuccessful; error thrown = ' + err.message);\n retObj['retMsg'].unshift(`${uName} is not a valid unit. ` +\n `${err.message}`);\n }\n } // end if the unit was not found as a unit name\n } // end if a unit expression was specified\n\n return retObj;\n\n } // end getSpecifiedUnit\n\n\n /**\n * This method retrieves a list of units commensurable, i.e., that can be\n * converted from and to, a specified unit. Returns an error if the \"from\"\n * unit cannot be found.\n *\n * @param fromName the name/unit string of the \"from\" unit\n * @returns an array containing two elements;\n * first element is the list of commensurable units if any were found\n * second element is an error message if the \"from\" unit is not found\n */\n commensurablesList(fromName) {\n\n let retMsg = [];\n let commUnits = null ;\n let parseResp = this.getSpecifiedUnit(fromName, 'validate', false);\n let fromUnit = parseResp['unit'];\n if (parseResp['retMsg'].length > 0)\n retMsg = parseResp['retMsg'] ;\n if (!fromUnit) {\n retMsg.push(`Could not find unit ${fromName}.`);\n }\n else {\n let dimVec = null ;\n let fromDim = fromUnit.getProperty('dim_');\n if (!fromDim) {\n retMsg.push('No commensurable units were found for ' + fromName) ;\n }\n else {\n try {\n dimVec = fromDim.getProperty('dimVec_');\n }\n catch (err) {\n retMsg.push(err.message);\n if (err.message ===\n \"Dimension does not have requested property(dimVec_)\")\n dimVec = null;\n }\n if (dimVec) {\n let utab = UnitTables.getInstance();\n commUnits = utab.getUnitsByDimension(dimVec);\n }\n } // end if the from unit has a dimension vector\n } // end if we found a \"from\" unit\n return [commUnits , retMsg];\n } // end commensurablesList\n\n} // end UcumLhcUtils class\n\n\n/**\n * This function exists ONLY until the original UcumLhcUtils constructor\n * is called for the first time. It's defined here in case getInstance\n * is called before the constructor. This calls the constructor.\n *\n * The constructor redefines the getInstance function to return the\n * singleton UcumLhcUtils object. This is based on the UnitTables singleton\n * implementation; see more detail in the UnitTables constructor description.\n *\n * NO LONGER TRUE - not implemented as a singleton. This method retained to\n * avoid problems with calls to it that exist throughout the code.\n *\n * @return the (formerly singleton) UcumLhcUtils object.\n */\nUcumLhcUtils.getInstance = function(){\n return new UcumLhcUtils();\n} ;\n\n\n\n\n"],"file":"ucumLhcUtils.js"}
|
package/source-cjs/unit.js
CHANGED
|
@@ -370,8 +370,8 @@ class Unit {
|
|
|
370
370
|
|
|
371
371
|
convertFrom(num, fromUnit) {
|
|
372
372
|
let newNum = 0.0;
|
|
373
|
-
if (this.isArbitrary_) throw new Error(`Attempt to convert arbitrary unit ${this.
|
|
374
|
-
if (fromUnit.isArbitrary_) throw new Error(`Attempt to convert
|
|
373
|
+
if (this.isArbitrary_) throw new Error(`Attempt to convert to arbitrary unit "${this.csCode_}"`);
|
|
374
|
+
if (fromUnit.isArbitrary_) throw new Error(`Attempt to convert arbitrary unit "${fromUnit.csCode_}"`); // reject request if both units have dimensions that are not equal
|
|
375
375
|
|
|
376
376
|
if (fromUnit.dim_ && this.dim_ && !fromUnit.dim_.equals(this.dim_)) {
|
|
377
377
|
// check first to see if a mole<->mass conversion is appropriate
|
|
@@ -393,40 +393,28 @@ class Unit {
|
|
|
393
393
|
}
|
|
394
394
|
|
|
395
395
|
let fromCnv = fromUnit.cnv_;
|
|
396
|
-
let fromMag = fromUnit.magnitude_;
|
|
397
|
-
|
|
398
|
-
// "from" unit's magnitude by the number passed in and then divide
|
|
399
|
-
// that result by this unit's magnitude. Do this for units with
|
|
400
|
-
// and without dimension vectors. PROBLEM with 2 non-commensurable
|
|
401
|
-
// units with no dimension vector or function, e.g., byte to mol
|
|
402
|
-
|
|
403
|
-
if (fromCnv === this.cnv_) {
|
|
404
|
-
newNum = num * fromMag / this.magnitude_;
|
|
405
|
-
} // else use a function to get the number to be returned
|
|
406
|
-
else {
|
|
407
|
-
let x = 0.0;
|
|
408
|
-
|
|
409
|
-
if (fromCnv != null) {
|
|
410
|
-
// turn num * fromUnit.magnitude into its ratio scale equivalent,
|
|
411
|
-
// e.g., convert Celsius to Kelvin
|
|
412
|
-
let fromFunc = _ucumFunctions.default.forName(fromCnv);
|
|
413
|
-
|
|
414
|
-
x = fromFunc.cnvFrom(num * fromUnit.cnvPfx_) * fromMag; //x = fromFunc.cnvFrom(num * fromMag) * fromUnit.cnvPfx_;
|
|
415
|
-
} else {
|
|
416
|
-
x = num * fromMag;
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
if (this.cnv_ != null) {
|
|
420
|
-
// turn mag * origUnit on ratio scale into a non-ratio unit,
|
|
421
|
-
// e.g. convert Kelvin to Fahrenheit
|
|
422
|
-
let toFunc = _ucumFunctions.default.forName(this.cnv_);
|
|
423
|
-
|
|
424
|
-
newNum = toFunc.cnvTo(x / this.magnitude_) / this.cnvPfx_;
|
|
425
|
-
} else {
|
|
426
|
-
newNum = x / this.magnitude_;
|
|
427
|
-
}
|
|
428
|
-
} // end if either unit has a conversion function
|
|
396
|
+
let fromMag = fromUnit.magnitude_;
|
|
397
|
+
let x;
|
|
429
398
|
|
|
399
|
+
if (fromCnv != null) {
|
|
400
|
+
// turn num * fromUnit.magnitude into its ratio scale equivalent,
|
|
401
|
+
// e.g., convert Celsius to Kelvin
|
|
402
|
+
let fromFunc = _ucumFunctions.default.forName(fromCnv);
|
|
403
|
+
|
|
404
|
+
x = fromFunc.cnvFrom(num * fromUnit.cnvPfx_) * fromMag; //x = fromFunc.cnvFrom(num * fromMag) * fromUnit.cnvPfx_;
|
|
405
|
+
} else {
|
|
406
|
+
x = num * fromMag;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
if (this.cnv_ != null) {
|
|
410
|
+
// turn mag * origUnit on ratio scale into a non-ratio unit,
|
|
411
|
+
// e.g. convert Kelvin to Fahrenheit
|
|
412
|
+
let toFunc = _ucumFunctions.default.forName(this.cnv_);
|
|
413
|
+
|
|
414
|
+
newNum = toFunc.cnvTo(x / this.magnitude_) / this.cnvPfx_;
|
|
415
|
+
} else {
|
|
416
|
+
newNum = x / this.magnitude_;
|
|
417
|
+
}
|
|
430
418
|
|
|
431
419
|
return newNum;
|
|
432
420
|
} // end convertFrom
|
|
@@ -633,6 +621,7 @@ class Unit {
|
|
|
633
621
|
else if (unit2.cnv_ != null) {
|
|
634
622
|
if (!retUnit.dim_ || retUnit.dim_.isZero()) {
|
|
635
623
|
retUnit.cnvPfx_ = unit2.cnvPfx_ * retUnit.magnitude_;
|
|
624
|
+
retUnit.magnitude_ = unit2.magnitude_;
|
|
636
625
|
retUnit.cnv_ = unit2.cnv_;
|
|
637
626
|
} else throw new Error(`Attempt to multiply non-ratio unit ${unit2.name_}`);
|
|
638
627
|
} // end if unit2 has a conversion function
|
|
@@ -666,7 +655,9 @@ class Unit {
|
|
|
666
655
|
// if (!retUnit.isMole_)
|
|
667
656
|
// retUnit.isMole_ = unit2.isMole_ ;
|
|
668
657
|
|
|
669
|
-
if (!retUnit.isArbitrary_) retUnit.isArbitrary_ = unit2.isArbitrary_;
|
|
658
|
+
if (!retUnit.isArbitrary_) retUnit.isArbitrary_ = unit2.isArbitrary_; // Likewise for special units
|
|
659
|
+
|
|
660
|
+
if (!retUnit.isSpecial_) retUnit.isSpecial_ = unit2.isSpecial_;
|
|
670
661
|
return retUnit;
|
|
671
662
|
} // end multiplyThese
|
|
672
663
|
|