华西海圻ELN前端工程
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

35 lines
912 B

  1. // massUnitUtils.js
  2. const toGramFactor = {
  3. 'pg': 1e-12,
  4. 'ng': 1e-9,
  5. 'ug': 1e-6,
  6. 'mg': 0.001,
  7. 'g': 1,
  8. 'kg': 1000
  9. };
  10. const validUnits = Object.keys(toGramFactor);
  11. export function isMassUnit(unit) {
  12. if (typeof unit !== 'string') return false;
  13. return validUnits.includes(unit.toLowerCase());
  14. }
  15. function toGrams(value, unit) {
  16. if (typeof value !== 'number' || isNaN(value)) {
  17. throw new Error('值必须是有效数字');
  18. }
  19. const lowerUnit = unit.toLowerCase();
  20. if (!isMassUnit(lowerUnit)) {
  21. throw new Error(`无效的质量单位: ${unit}`);
  22. }
  23. return value * toGramFactor[lowerUnit];
  24. }
  25. export function compareMass(value1, unit1, value2, unit2) {
  26. const grams1 = toGrams(value1, unit1);
  27. const grams2 = toGrams(value2, unit2);
  28. if (grams1 > grams2) return 1;
  29. if (Math.abs(grams1 - grams2) < 1e-12) return 0;
  30. return -1;
  31. }