Skip to content

Instantly share code, notes, and snippets.

@LeeDDHH
Created December 5, 2020 09:08
Show Gist options
  • Save LeeDDHH/f6317d555b6ef0bdf9ef6185af7be26a to your computer and use it in GitHub Desktop.
Save LeeDDHH/f6317d555b6ef0bdf9ef6185af7be26a to your computer and use it in GitHub Desktop.
compare version source and target
if (process.argv.length < 4) {
console.log('number of arguments is short');
return;
}
const sourceVersion = process.argv[2];
const targetVersion = process.argv[3];
/**
* Function
* @param {string} source - "1.0.1"
* @param {string} target - "1.0.0"
* @return {number} - -1, 0, 1
*/
const compareVersion = (source, target) => {
let sourceParts = source.split('.');
let targetParts = target.split('.');
sourceParts = sourceParts.map(Number);
targetParts = targetParts.map(Number);
let limit = Math.max(sourceParts.length, targetParts.length);
let sPart, tPart;
let result = 0;
while(limit--){
sPart = sourceParts.shift() || 0;
tPart = targetParts.shift() || 0;
if(sPart !== tPart){
result = sPart > tPart ? 1 : -1;
break;
}
}
return result;
}
const result = compareVersion(sourceVersion, targetVersion);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment