Skip to content

Instantly share code, notes, and snippets.

@ming-chu
Last active October 4, 2024 04:26
Show Gist options
  • Save ming-chu/bd058dc28004701a0670073aa573cace to your computer and use it in GitHub Desktop.
Save ming-chu/bd058dc28004701a0670073aa573cace to your computer and use it in GitHub Desktop.
Compare version name in Dart for DartPad share
// to see more: https://stackoverflow.com/a/79051433/5881669
import 'dart:math';
import 'package:collection/collection.dart';
void main() {
print(compareVersion('1.2.3', '12.3')); // -1
print(compareVersion('12.3', '1.2.3')); // 1
print(compareVersion('1.2.3', '1.2.3')); // 0
}
int compareVersion(String version1, String version2) {
final nums1 = version1.split('.').map(BigInt.parse).toList();
final nums2 = version2.split('.').map(BigInt.parse).toList();
// pad with 0 for the shorter list
if (nums1.length != nums2.length) {
final diff = nums1.length - nums2.length;
(diff > 0 ? nums2 : nums1).addAll(List.filled(diff.abs(), BigInt.zero));
}
final maxBitLengths = IterableZip([nums1, nums2])
.map((item) => max(item[0].bitLength, item[1].bitLength))
.toList();
final v1Num = nums1.reduceIndexed((i, a, b) => a << maxBitLengths[i] | b);
final v2Num = nums2.reduceIndexed((i, a, b) => a << maxBitLengths[i] | b);
return min(max(v1Num.compareTo(v2Num), -1), 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment