| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | */ |
| 7 | |
| 8 | /** An array of parts of the version, like [Major, Minor, Subminor] */ |
| 9 | export type ParsedVersion = Array<number>; |
| 10 | |
| 11 | /** Comparator for parsed version. Return -1 if a < b, 1 if a > b, and 0 if a == b */ |
| 12 | export function compareVersions(a: ParsedVersion, b: ParsedVersion): -1 | 0 | 1 { |
| 13 | if (a.length === 0 && b.length === 0) { |
| 14 | return 0; |
| 15 | } |
| 16 | if (b.length === 0) { |
| 17 | return 1; |
| 18 | } |
| 19 | if (a.length === 0) { |
| 20 | return -1; |
| 21 | } |
| 22 | |
| 23 | return a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : compareVersions(a.slice(1), b.slice(1)); |
| 24 | } |
| 25 | |
| 26 | /** |
| 27 | * Given a version ordinal label like V1, V0.1, V0.10 etc, extract the parts like [1], [0, 1], [0, 10] etc |
| 28 | * This IGNORES any leading/trailing non-numeric parts. |
| 29 | */ |
| 30 | export function parseVersionParts(ordinal: string): ParsedVersion { |
| 31 | try { |
| 32 | const numbers = /^[a-zA-Z\-_]*(\d+(?:\.\d+)*)[a-zA-Z\-_]*$/.exec(ordinal); |
| 33 | return numbers?.[1].split('.').map(part => parseInt(part, 10)) ?? []; |
| 34 | } catch { |
| 35 | return []; |
| 36 | } |
| 37 | } |
| 38 | |