|
|
- // massUnitUtils.js
- const toGramFactor = {
- 'pg': 1e-12,
- 'ng': 1e-9,
- 'ug': 1e-6,
- 'mg': 0.001,
- 'g': 1,
- 'kg': 1000
- };
-
- const validUnits = Object.keys(toGramFactor);
-
- export function isMassUnit(unit) {
- if (typeof unit !== 'string') return false;
- return validUnits.includes(unit.toLowerCase());
- }
-
- function toGrams(value, unit) {
- if (typeof value !== 'number' || isNaN(value)) {
- throw new Error('值必须是有效数字');
- }
- const lowerUnit = unit.toLowerCase();
- if (!isMassUnit(lowerUnit)) {
- throw new Error(`无效的质量单位: ${unit}`);
- }
- return value * toGramFactor[lowerUnit];
- }
-
- export function compareMass(value1, unit1, value2, unit2) {
- const grams1 = toGrams(value1, unit1);
- const grams2 = toGrams(value2, unit2);
-
- if (grams1 > grams2) return 1;
- if (Math.abs(grams1 - grams2) < 1e-12) return 0;
- return -1;
- }
|