Skip to content

Instantly share code, notes, and snippets.

@FokkeZB
Created April 29, 2013 09:52
Show Gist options
  • Save FokkeZB/5480698 to your computer and use it in GitHub Desktop.
Save FokkeZB/5480698 to your computer and use it in GitHub Desktop.
CommonJS version comparison library for Titanium
var version = require('version');
if (version.atLeast('3.1.0')) {
Ti.API.info('Your Ti.version is at least 3.1.0');
}
if (version.olderThan('3.1.0')) {
Ti.API.info('Your Ti.version is older then 3.1.0');
}
// Returns TRUE if first version is at least second version
var result = version.atLeast('3.1.0', '3.1.0'); // TRUE
// Returns TRUE if first version is at older than second version
var result = version.olderThan('3.0.0', '3.0.0'); // FALSE
// Returns 0 if equal
// Returns -1 if 'a' smaller than 'b'
// Returns 1 if 'a' bigger than 'b'
var result = version.compare(a,b);
function compare(a, b) {
var i, cmp, len, re = /(\.0)+[^\.]*$/;
a = (a + '').replace(re, '').split('.');
b = (b + '').replace(re, '').split('.');
len = Math.min(a.length, b.length);
for( i = 0; i < len; i++ ) {
cmp = parseInt(a[i], 10) - parseInt(b[i], 10);
if( cmp !== 0 ) {
return cmp;
}
}
return a.length - b.length;
}
function atLeast(a, b) {
if (!b) {
b = a;
a = Ti.version;
}
return compare(a, b) >= 0;
}
function olderThan(a, b) {
if (!b) {
b = a;
a = Ti.version;
}
return compare(a, b) < 0;
}
exports.compare = compare;
exports.atLeast = atLeast;
exports.olderThan = olderThan;

The Titanium docs tell you Ti.version is a number, but it's not... it's a string, that can include stuff like beta, GA etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment