// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
import type { SemVer } from "./types.ts";
import {
  checkIdentifier,
  compareIdentifier,
  compareNumber,
} from "./_shared.ts";

/**
 * Compare two semantic version objects.
 *
 * Returns `0` if `s0 === s1`, or `1` if `s0` is greater, or `-1` if `s1` is
 * greater.
 *
 * Sorts in ascending order if passed to `Array.sort()`,
 *
 * @example Usage
 * ```ts
 * import { parse, compare } from "@std/semver";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const s0 = parse("1.2.3");
 * const s1 = parse("1.2.4");
 *
 * assertEquals(compare(s0, s1), -1);
 * assertEquals(compare(s1, s0), 1);
 * assertEquals(compare(s0, s0), 0);
 * ```
 *
 * @param s0 The first SemVer to compare
 * @param s1 The second SemVer to compare
 * @returns `1` if `s0` is greater, `0` if equal, or `-1` if `s1` is greater
 */
export function compare(
  s0: SemVer,
  s1: SemVer,
): 1 | 0 | -1 {
  if (s0 === s1) return 0;
  return (
    compareNumber(s0.major, s1.major) ||
    compareNumber(s0.minor, s1.minor) ||
    compareNumber(s0.patch, s1.patch) ||
    checkIdentifier(s0.prerelease, s1.prerelease) ||
    compareIdentifier(s0.prerelease, s1.prerelease)
  );
}

// denoCacheMetadata={"headers":{"content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","x-content-type-options":"nosniff","server":"cloudflare","cross-origin-resource-policy":"cross-origin","x-robots-tag":"noindex","set-cookie":"__cf_bm=U.TK6GengVh5cD9RfZMgbHctlE1WR_kgkZD39yvFFSY-1785241875.1541388-1.0.1.1-kp8KAh9_31OxEPUize9Q_7g4CFrS9QPLEfmwA5HI52lWZEoudcShsdmj9E.UFGbZtrfpL2dicAJWZf4HHmWMkb7pJkS4963e7rMpMJCaD4iDrJFY.d5R1eWRY8hsDNJY; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","alt-svc":"h3=\":443\"; ma=86400","accept-ranges":"bytes","cache-control":"public, max-age=31536000, immutable","date":"Tue, 28 Jul 2026 12:31:15 GMT","age":"1336395","content-type":"text/typescript","x-jsr-backend":"modules","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","cf-ray":"a223e657ba4d7db6-LAX","access-control-allow-origin":"*","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=KLUJGT3omGZlSuwl3pG1xa%2BSzkXt5Rdo%2BzvflAcGvAQlGmCsqW3goCR0k8%2B3i5CbeJ7PWO3SxGWnf2iSkTwPQWYtLpL9Bcggelfn7oXVyx%2BKQ2SlyIIXJ0w%3D\"}]}","cf-cache-status":"HIT","vary":"Origin","etag":"\"2fab38256d5b615371cad2a71d1631c3\"","content-length":"1276","access-control-expose-headers":"*"},"url":"https://jsr.io/@std/semver/0.224.3/compare.ts","time":1785241875}