-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathversion.ts
72 lines (58 loc) · 1.94 KB
/
version.ts
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
export type VersionArray = [number, number, number];
const versionNames = ["major", "minor", "patch"] as const;
export class Version {
constructor(private readonly version: VersionArray) {
const isValid = Version.isValidVersion(this.version);
if (isValid !== true) {
throw isValid;
}
}
/** This checks if any type is a valid version array at runtime
*
* @param version the version to check
*/
private static isValidVersion(version: Version | any): true | Error {
if (!Array.isArray(version)) {
return new Error("Version object is not an Array");
}
if (version.length !== 3) {
return new Error(`Version array has ${version.length} entries, but expected 3`);
}
for (const index in version as VersionArray) {
const num = version[index];
if (!Number.isInteger(num)) {
const name = versionNames[index];
return new Error(`${name} version component is not a number: '${num}'`);
}
}
return true;
}
/** This compares two versions
* - if the first one is bigger, a value > 0 is returned
* - if they are the same, 0 is returned
* - if the first one is smaller, a value < 0 is returned
* @param version1
* @param version2
*/
private static compareImpl([major1, minor1, patch1]: VersionArray, [major2, minor2, patch2]: VersionArray): number {
if (major1 !== major2) {
return major1 - major2;
}
if (minor1 !== minor2) {
return minor1 - minor2;
}
return patch1 - patch2;
}
compareWithOther(otherVersion: Version): number {
return Version.compareImpl(this.version, otherVersion.version);
}
compare(otherVersion: VersionArray): number {
return Version.compareImpl(this.version, otherVersion);
}
private static versionToString([major, minor, patch]: VersionArray): string {
return `${major}.${minor}.${patch}`;
}
toString(): string {
return Version.versionToString(this.version);
}
}