convert.js 998 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /**
  2. * convert time into another unit
  3. */
  4. function convert(val, sourceUnitName, destinationUnitName){
  5. destinationUnitName = destinationUnitName || 'ms';
  6. return (val * getUnit(sourceUnitName)) / getUnit(destinationUnitName);
  7. }
  8. //TODO: maybe extract to a separate module
  9. function getUnit(unitName){
  10. switch(unitName){
  11. case 'ms':
  12. case 'millisecond':
  13. return 1;
  14. case 's':
  15. case 'second':
  16. return 1000;
  17. case 'm':
  18. case 'minute':
  19. return 60000;
  20. case 'h':
  21. case 'hour':
  22. return 3600000;
  23. case 'd':
  24. case 'day':
  25. return 86400000;
  26. case 'w':
  27. case 'week':
  28. return 604800000;
  29. default:
  30. throw new Error('"'+ unitName + '" is not a valid unit');
  31. }
  32. }
  33. module.exports = convert;