UNPKG

@elgato/streamdeck

Version:

The official Node.js SDK for creating Stream Deck plugins.

60 lines (59 loc) 2.18 kB
/** * Provides information for a version, as parsed from a string denoted as a collection of numbers separated by a period, for example `1.45.2`, `4.0.2.13098`. Parsing is opinionated * and strings should strictly conform to the format `{major}[.{minor}[.{patch}[.{build}]]]`; version numbers that form the version are optional, and when `undefined` will default to * 0, for example the `minor`, `patch`, or `build` number may be omitted. * * NB: This implementation should be considered fit-for-purpose, and should be used sparing. */ export class Version { /** * Build version number. */ build; /** * Major version number. */ major; /** * Minor version number. */ minor; /** * Patch version number. */ patch; /** * Initializes a new instance of the {@link Version} class. * @param value Value to parse the version from. */ constructor(value) { const result = value.match(/^(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?(?:\.(0|[1-9]\d*))?(?:\.(0|[1-9]\d*))?$/); if (result === null) { throw new Error(`Invalid format; expected "{major}[.{minor}[.{patch}[.{build}]]]" but was "${value}"`); } [, this.major, this.minor, this.patch, this.build] = [...result.map((value) => parseInt(value) || 0)]; } /** * Compares this instance to the {@link other} {@link Version}. * @param other The {@link Version} to compare to. * @returns `-1` when this instance is less than the {@link other}, `1` when this instance is greater than {@link other}, otherwise `0`. */ compareTo(other) { const segments = ({ major, minor, build, patch }) => [major, minor, build, patch]; const thisSegments = segments(this); const otherSegments = segments(other); for (let i = 0; i < 4; i++) { if (thisSegments[i] < otherSegments[i]) { return -1; } else if (thisSegments[i] > otherSegments[i]) { return 1; } } return 0; } /** @inheritdoc */ toString() { return `${this.major}.${this.minor}`; } }