All files / semver / format.ts

100.00% Branches 4/4
100.00% Lines 13/13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 
 
 
 
x3094
x3094
x3094
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x28
x1050
x1050
x1050
x1050
x1050
 
x1050
x4200
x4200
x1050




































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.
import type { SemVer } from "./types.ts";

function formatNumber(value: number) {
  return value.toFixed(0);
}

/**
 * Format a SemVer object into a string.
 *
 * @example Usage
 * ```ts
 * import { format } from "@std/semver/format";
 * import { assertEquals } from "@std/assert";
 *
 * const semver = {
 *   major: 1,
 *   minor: 2,
 *   patch: 3,
 * };
 * assertEquals(format(semver), "1.2.3");
 * ```
 *
 * @param version The SemVer to format
 * @returns The string representation of a semantic version.
 */
export function format(version: SemVer): string {
  const major = formatNumber(version.major);
  const minor = formatNumber(version.minor);
  const patch = formatNumber(version.patch);
  const pre = version.prerelease?.join(".") ?? "";
  const build = version.build?.join(".") ?? "";

  const primary = `${major}.${minor}.${patch}`;
  const release = [primary, pre].filter((v) => v).join("-");
  return [release, build].filter((v) => v).join("+");
}