Skip to content

Instantly share code, notes, and snippets.

@niquenen
Last active January 6, 2025 16:42
Show Gist options
  • Save niquenen/df3b95f3bd60602618fbe5c50c49b34b to your computer and use it in GitHub Desktop.
Save niquenen/df3b95f3bd60602618fbe5c50c49b34b to your computer and use it in GitHub Desktop.
TypeScript function to create semantic version number
/**
* Generates a semantic version number from the given {@link major},
* {@link minor}, and {@link patch} numbers.
*
* @remarks
* Inspired by the PHP [`PHP_VERSION_ID`][l2] constant to get the current
* version as an integer.
*
* See:
*
* - [PHP: phpversion - Manual][l1]
* - [PHP: Predefined Constants - Manual][l2]
*
* [l1]: https://php.net/manual/function.phpversion.php
* [l2]: https://php.net/manual/reserved.constants.php#constant.php-version-id
*
* @example
* ```typescript
* getSemVer(1, 2, 3); // Returns: 10203
* getSemVer(1); // Returns: 10000
* getSemVer(1, 101); // Throws Error: Minor must be less than or equal to 100.
* getSemVer(1, 0.3, 5); // Throws Error: All parameters must be integers.
*
* // Comparing versions
* const version1 = getSemVer(1, 2, 3); // 10203
* const version2 = getSemVer(1, 3, 0); // 10300
* console.log(version1 < version2); // true
* ```
*
* @throws If any of the parameters are not integers.
* @throws If the minor or patch numbers are greater than 100.
* @param major - The major version number.
* @param minor - The minor version number. Defaults to `0`.
* @param patch - The patch version number. Defaults to `0`.
* @returns The semantic version number as a single integer.
*/
export function createSemVer(
major: number,
minor: number = 0,
patch: number = 0
): number
{
const isIntegers: boolean = Number.isInteger(major) && Number.isInteger(
minor
) && Number.isInteger(patch);
if (!isIntegers) {
throw new Error('All parameters must be integers.');
}
else if (minor > 100 || patch > 100) {
throw new Error(
'Minor and patch numbers must be less than or equal to 100.'
);
}
return (major * 10_000) + (minor * 100) + patch;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment