2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2024-04-10 02:43:44 +00:00
|
|
|
// This module is browser compatible.
|
2023-06-12 03:47:03 +00:00
|
|
|
import type { SemVer } from "./types.ts";
|
|
|
|
import {
|
|
|
|
checkIdentifier,
|
|
|
|
compareIdentifier,
|
|
|
|
compareNumber,
|
|
|
|
} from "./_shared.ts";
|
|
|
|
|
|
|
|
/**
|
2024-06-28 05:47:34 +00:00
|
|
|
* Compare two SemVers.
|
2023-06-12 03:47:03 +00:00
|
|
|
*
|
2024-08-19 04:33:42 +00:00
|
|
|
* Returns `0` if `version1` equals `version2`, or `1` if `version1` is greater, or `-1` if `version2` is
|
2023-06-12 03:47:03 +00:00
|
|
|
* greater.
|
|
|
|
*
|
2024-06-28 05:47:34 +00:00
|
|
|
* Sorts in ascending order if passed to {@linkcode Array.sort}.
|
2024-05-27 10:03:20 +00:00
|
|
|
*
|
|
|
|
* @example Usage
|
|
|
|
* ```ts
|
|
|
|
* import { parse, compare } from "@std/semver";
|
refactor(assert,async,bytes,cli,collections,crypto,csv,data-structures,datetime,dotenv,encoding,expect,fmt,front-matter,fs,html,http,ini,internal,io,json,jsonc,log,media-types,msgpack,net,path,semver,streams,testing,text,toml,ulid,url,uuid,webgpu,yaml): import from `@std/assert` (#5199)
* refactor: import from `@std/assert`
* update
2024-06-30 08:30:10 +00:00
|
|
|
* import { assertEquals } from "@std/assert";
|
2024-05-27 10:03:20 +00:00
|
|
|
*
|
2024-08-19 04:33:42 +00:00
|
|
|
* const version1 = parse("1.2.3");
|
|
|
|
* const version2 = parse("1.2.4");
|
2024-05-27 10:03:20 +00:00
|
|
|
*
|
2024-08-19 04:33:42 +00:00
|
|
|
* assertEquals(compare(version1, version2), -1);
|
|
|
|
* assertEquals(compare(version2, version1), 1);
|
|
|
|
* assertEquals(compare(version1, version1), 0);
|
2024-05-27 10:03:20 +00:00
|
|
|
* ```
|
|
|
|
*
|
2024-08-19 04:33:42 +00:00
|
|
|
* @param version1 The first SemVer to compare
|
|
|
|
* @param version2 The second SemVer to compare
|
|
|
|
* @returns `1` if `version1` is greater, `0` if equal, or `-1` if `version2` is greater
|
2023-06-12 03:47:03 +00:00
|
|
|
*/
|
2024-08-19 04:33:42 +00:00
|
|
|
export function compare(version1: SemVer, version2: SemVer): 1 | 0 | -1 {
|
|
|
|
if (version1 === version2) return 0;
|
2023-08-31 10:44:22 +00:00
|
|
|
return (
|
2024-08-19 04:33:42 +00:00
|
|
|
compareNumber(version1.major, version2.major) ||
|
|
|
|
compareNumber(version1.minor, version2.minor) ||
|
|
|
|
compareNumber(version1.patch, version2.patch) ||
|
|
|
|
checkIdentifier(version1.prerelease, version2.prerelease) ||
|
|
|
|
compareIdentifier(version1.prerelease, version2.prerelease)
|
2023-08-31 10:44:22 +00:00
|
|
|
);
|
2023-06-12 03:47:03 +00:00
|
|
|
}
|