Skip to content

Instantly share code, notes, and snippets.

@p0rsche
Created November 7, 2023 08:38
Show Gist options
  • Select an option

  • Save p0rsche/871b30712d5fc859d5e323d3e300bb4a to your computer and use it in GitHub Desktop.

Select an option

Save p0rsche/871b30712d5fc859d5e323d3e300bb4a to your computer and use it in GitHub Desktop.

Revisions

  1. p0rsche created this gist Nov 7, 2023.
    35 changes: 35 additions & 0 deletions versionComparator.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    const assert = require('node:assert');

    const parseInt = (n) => Number.parseInt(n)

    function versionComparator(v1, v2) {
    const v1arr = v1.split('.').map(parseInt);
    const v1arrlen = v1arr.length;
    const v2arr = v2.split('.').map(parseInt);
    const v2arrlen = v2arr.length;

    // preventing out of bounds
    const len = v1arrlen > v2arrlen ? v2arrlen : v1arrlen;

    for(let i = 0; i < len; i++) {
    if (v1arr[i] === v2arr[i]) {
    continue;
    }
    return v1arr[i] > v2arr[i] ? 1 : -1;
    }

    return 0
    }

    const versions = [
    ['1.0.1', '1.0.01', 0],
    ['1.0.1', '0.1.0.1.0', 1],
    ['1.0.2', '1.0.0.2', 1],
    ['2.1.0', '2.4.6.001', -1],
    ]

    versions.forEach(([v1, v2, answer]) => {
    const result = versionComparator(v1, v2);
    console.log(v1, v2, result);
    assert.equal(result, answer)
    });