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.

59 lines
1.4 KiB

  1. 'use strict';
  2. export namespace Versions {
  3. declare type VersionComparisonResult = -1 | 0 | 1;
  4. export interface Version {
  5. major: number;
  6. minor: number;
  7. patch: number;
  8. pre?: string;
  9. }
  10. export function compare(v1: string | Version, v2: string | Version): VersionComparisonResult {
  11. if (typeof v1 === 'string') {
  12. v1 = fromString(v1);
  13. }
  14. if (typeof v2 === 'string') {
  15. v2 = fromString(v2);
  16. }
  17. if (v1.major > v2.major) return 1;
  18. if (v1.major < v2.major) return -1;
  19. if (v1.minor > v2.minor) return 1;
  20. if (v1.minor < v2.minor) return -1;
  21. if (v1.patch > v2.patch) return 1;
  22. if (v1.patch < v2.patch) return -1;
  23. if (v1.pre === undefined && v2.pre !== undefined) return 1;
  24. if (v1.pre !== undefined && v2.pre === undefined) return -1;
  25. if (v1.pre !== undefined && v2.pre !== undefined) {
  26. return v1.pre.localeCompare(v2.pre) as VersionComparisonResult;
  27. }
  28. return 0;
  29. }
  30. export function from(
  31. major: string | number,
  32. minor: string | number,
  33. patch?: string | number,
  34. pre?: string
  35. ): Version {
  36. return {
  37. major: typeof major === 'string' ? parseInt(major, 10) : major,
  38. minor: typeof minor === 'string' ? parseInt(minor, 10) : minor,
  39. patch: patch == null ? 0 : typeof patch === 'string' ? parseInt(patch, 10) : patch,
  40. pre: pre
  41. };
  42. }
  43. export function fromString(version: string): Version {
  44. const [ver, pre] = version.split('-');
  45. const [major, minor, patch] = ver.split('.');
  46. return from(major, minor, patch, pre);
  47. }
  48. }